gpt4 book ai didi

python - 如何使用 Pandas 添加 python 中未列出的数据帧循环的组合

转载 作者:行者123 更新时间:2023-12-01 07:09:17 27 4
gpt4 key购买 nike

a = [["a1","b1"],["a2","b2"],["a3","b3"],["a4","b4"],["a5","b5"]]

df = pd.DataFrame({'A' : ["a1","a2","a3","a4"], 'B' : ["b1","b2","b3", "b4"] , 'mean' : ["13.4","12,1","10.0","11.5"]})

如何将列表“a”中没有的组合添加到数据框行?

我想使用contains()isin()

预期结果不存在的列表将使用默认值 0 填充值的平均值。

pd.DataFrame({'A' : ["a1","a2","a3","a4","a5"], B' : ["b1","b2","b3", "b4","b5"] ,'mean' : ["13.4","12,1","10.0","11.5", "0"]}) 

最佳答案

创建DataFrame构造函数和DataFrame.append到原始,然后通过 DataFrame.drop_duplicates 删除重复项通过指定列并最后用 fillna 替换缺失值:

a = [["a1","b1"],["a2","b2"],["a3","b3"],["a4","b4"],["a5","b5"]]

df1 = df.append(pd.DataFrame(a,columns=['A','B'])).drop_duplicates(subset=['A','B']).fillna(0)

print (df1)
A B mean
0 a1 b1 13.4
1 a2 b2 12,1
2 a3 b3 10.0
3 a4 b4 11.5
4 a5 b5 0

另一个关于合并的想法:

df1 = pd.DataFrame(a, columns=['A','B']).merge(df, how='left').fillna(0)

关于python - 如何使用 Pandas 添加 python 中未列出的数据帧循环的组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58299566/

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