我有一个现有的 DataFrame,以及一个计算几列以添加到该 DataFrame 的方法。我目前使用pd.concat([left, right], axis=1). 然而,当我第二次调用此方法时,它会再次添加列(具有相同的名称)。
使用以下示例数据框left和right:
left = pd.DataFrame({'one': [1, 2, 3], 'two': [2, 3, 4]})
print(left)
one two
0 1 2
1 2 3
2 3 4
right = pd.DataFrame({'one': [22, 22, 22], 'NEW': [33, 33, 33]})
print(right)
one NEW
0 22 33
1 22 33
2 22 33
Run Code Online (Sandbox Code Playgroud)
我正在寻找一种foo方法,其结果如下:
left = left.foo(right) # or foo(left, right)
print(left)
one two NEW
0 22 2 33
1 22 3 33
2 22 4 33
Run Code Online (Sandbox Code Playgroud)
而且,重要的是,如果我left.foo(right)第二次调用,我希望结果保持不变。
pd.join当列已存在时引发错误,pd.concat不会覆盖现有列,pd.update仅覆盖现有列但不添加新列。
是否有一种函数/方法可以完成我想要的操作,或者我必须自己编写一个函数/方法?
解决方案:结合以下两个答案,对我有用的解决方案是:
result = left.\
drop(left.columns.intersection(right.columns), axis=1).\
join(right)
Run Code Online (Sandbox Code Playgroud)
然后采取intersection和列:dropmergeindex
left = left.drop(left.columns.intersection(right.columns),1).merge(right, left_index=True, right_index=True)
print(left)
two one NEW
0 2 22 33
1 3 22 33
2 4 22 33
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3315 次 |
| 最近记录: |