gpt4 book ai didi

Pandas dataFrame 追加并添加新列

转载 作者:行者123 更新时间:2023-12-05 04:11:07 31 4
gpt4 key购买 nike

当我在 for 循环中“找到”数据帧时,我试图将它们附加在一起,并添加额外的列。

我的意思是:

我有一个现有的数据框 X

a    b   c
1 2 3
5 6 7
9 10 11

我有一个 for 循环,它可以“找到”满足条件参数的某些行。然后我想将这些行添加到一个空框架中,其中包含额外的列。因此新的数据框架 Y 将是:

a   b   c  next
5 6 7 8

接下来是添加的新列。到目前为止,我尝试通过以下方式添加:

allInfo = pd.DataFrame(columns=[list(X), "next"])
allInfo = allInfo.append([a[a.apply(lambda x:someConditional,axis=1)], valueNext],ignore_index=True)

但这行不通。有没有简单的方法可以做到这一点?

谢谢!

最佳答案

我认为最好的方法是在循环中创建 DataFrames 列表并最后使用 concat它们与原始 df 一起。

final = pd.concat([df, df1, df2, df3,...])

但最好避免 pandas 中的所有循环,因为速度很慢。

df1 = df[df.a == 5].copy()
df1['next'] = 8
print (df1)
a b c next
1 5 6 7 8

df2 = df[df.a == 1].copy()
df2['next'] = 10
print (df2)
a b c next
0 1 2 3 10

dfs = [df, df1, df2]
final = pd.concat(dfs, ignore_index=True)
print (final)

a b c next
0 1 2 3 NaN
1 5 6 7 NaN
2 9 10 11 NaN
3 5 6 7 8.0
4 1 2 3 10.0

关于Pandas dataFrame 追加并添加新列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43349179/

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