python - Pandas 如何将列表列转换为多列?
问题描述
我有一个非常大的DataFrame,其中一列(COL)包含一个范围(即列表)的值。我想将此 COL 转换为标有特定数字的单独列,如果特定数字在 COL 中,则包含 1,否则为 0。
以下是我目前的做法。但是,对于大量的 OBSERVATIONS 和 MAX_VALUE,这会很慢。
import pandas as pd
import numpy as np
OBSERVATIONS = 100000 # number of values 600000
MAX_VALUE = 400 # 400
_ = pd.DataFrame({
'a':np.random.randint(2,20,OBSERVATIONS),
'b':np.random.randint(30,MAX_VALUE,OBSERVATIONS)
})
_['res'] = _.apply(lambda x: range(x['a'],x['b']),axis=1)
for i in range(MAX_VALUE):
_[f'{i}'] = _['res'].apply(lambda x: 1 if i in x else 0)
解决方案
您可以尝试进行计算,numpy
然后将numpy
数组插入数据框。这大约快 5 倍:
import pandas as pd
import numpy as np
import time
OBSERVATIONS = 100_000 # number of values 600000
MAX_VALUE = 400 # 400
_ = pd.DataFrame({
'a':np.random.randint(2,20,OBSERVATIONS),
'b':np.random.randint(30,MAX_VALUE,OBSERVATIONS)
})
_['res'] = _.apply(lambda x: range(x['a'],x['b']),axis=1)
res1 = _.copy()
start = time.time()
for i in range(MAX_VALUE):
res1[f'{i}'] = res1['res'].apply(lambda x: 1 if i in x else 0)
print(f'original: {time.time() - start}')
start = time.time()
z = np.zeros((len(_), MAX_VALUE), dtype=np.int64)
for i,r in enumerate(_.res):
z[i,range(r.start,r.stop)]=1
res2 = pd.concat([_, pd.DataFrame(z)], axis=1)
res2.columns = list(map(str, res2.columns))
print(f'new : {time.time() - start}')
assert res1.equals(res2)
输出:
original: 23.649751663208008
new : 4.586429595947266
推荐阅读
- mysql - 从数据库中检索值时,我可以在日期选择器中使用 ((TextField)selecteDOP.getEditor()).getText()
- c++ - const 类实例的 C++ 内存地址
- java - 如何将变量传递给另一个类java
- nexus - 无法在 nexus 2 中使用 CURl 上传
- xamarin - 如何为 Xamarin 创建通用库?
- hyperledger-fabric - 如何确定 Docker 映像中 Hyperledger Fabric 代码的版本?
- android - 如何在 iOS 和 Android 上尽可能快地制作 FCM?
- c# - 在datareader c#中执行命令
- javascript - 圆圈背景无法围绕图标放置
- javascript - 文档不会使用带有 mongoose 的 save() 方法保存