[英]Python Pandas - How to compare the column values in a df with column values of another df
[英]Compare the presence of a column in a DF into another DF, then fill
我有 2 个 DF,我想检查 df1["A"] 是否在 df2 中。 如果没有,则用 0 填充 df2["A"]。
我得到了它和丑陋的 for 循环,我尝试优化它,但我不知道如何去做。
testing_list = list(testing_df.columns)
for i in range(len(training_df.columns)):
if not training_df.columns[i] in testing_list:
testing_df[training_df.columns[i]] = 0
将DataFrame.reindex
与Index.union
创建的新列Index.union
:
testing_df = pd.DataFrame({
'A':list('abcdef'),
'B':[4,5,4,5,5,4],
'F':list('aaabbb')
})
training_df = pd.DataFrame({
'A':list('abcdef'),
'C':[7,8,9,4,2,3],
'D':[1,3,5,7,1,0],
})
cols = testing_df.columns.union(training_df.columns, sort=False)
df = testing_df.reindex(cols, axis=1, fill_value=0)
print (df)
A B F C D
0 a 4 a 0 0
1 b 5 a 0 0
2 c 4 a 0 0
3 d 5 b 0 0
4 e 5 b 0 0
5 f 4 b 0 0
如果要为具有排序列的两个 DataFrame 添加列,请使用DataFrame.align
:
testing_df, training_df = testing_df.align(training_df, fill_value=0)
print (testing_df)
A B C D F
0 a 4 0 0 a
1 b 5 0 0 a
2 c 4 0 0 a
3 d 5 0 0 b
4 e 5 0 0 b
5 f 4 0 0 b
print (training_df)
A B C D F
0 a 0 7 1 0
1 b 0 8 3 0
2 c 0 9 5 0
3 d 0 4 7 0
4 e 0 2 1 0
5 f 0 3 0 0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.