gpt4 book ai didi

python - 构建 Pandas DataFrame 时避免循环

转载 作者:太空宇宙 更新时间:2023-11-04 04:36:33 25 4
gpt4 key购买 nike

我有一个包含三列的初始 Pandas DataFrame,其中一列包含字符串列表。目标是将每一行拆分为与 obj 列中的项目一样多的元素,例如:

from    to      obj
--------------------
abc xyz [foo, bar]
def uvw [gee]
ghi rst [foo, bar, baz]

变成这样:

from    to      obj
--------------------
abc xyz foo
abc xyz bar
def uvw gee
ghi rst foo
ghi rst bar
ghi rst baz

目前我是这样做的:

transformed = pd.DataFrame(columns=['from', 'to', 'obj'])

for index, row in origin.iterrows():
for obj in row['obj']:
transformed = transformed.append(pd.Series({
'from': row['from'],
'to': row['to'],
'obj': obj
}), ignore_index=True)

除了慢得令人痛苦之外,这工作得很好。如果 origin 有 100,000 个元素,则计算 transformed 很容易需要长达一小时。

有没有一种矢量化的方法可以得到相同的结果,而不必求助于 Python 循环?

最佳答案

本质上,您是在根据您的列重复链接值。

所以你可以使用np.repeatitertools.chain作为适当的。该解决方案对于少量列是有效的,如您的示例所示。

import numpy as np
from itertools import chain

# set up dataframe
df = pd.DataFrame({'from': ['abc', 'def', 'gfhi'],
'to': ['xyz', 'uvw', 'rst'],
'obj': [['foo', 'bar'], ['gee'], ['foo', 'bar', 'baz']]})

# calculate length of each list in obj
lens = df['obj'].map(len)

# calculate result, repeating or chaining as appropriate
res = pd.DataFrame({'from': np.repeat(df['from'], lens),
'to': np.repeat(df['to'], lens),
'obj': list(chain.from_iterable(df['obj']))})

print(res)

from to obj
0 abc xyz foo
0 abc xyz bar
1 def uvw gee
2 gfhi rst foo
2 gfhi rst bar
2 gfhi rst baz

关于python - 构建 Pandas DataFrame 时避免循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51570474/

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