gpt4 book ai didi

python - Pandas 如何将列表的列变成多列?

转载 作者:行者123 更新时间:2023-12-01 06:49:37 26 4
gpt4 key购买 nike

我有一个非常大的 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

关于python - Pandas 如何将列表的列变成多列?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59078982/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com