我有一些数据正在尝试根据值合并。随着时间的推移,命名约定发生了变化,列名称中添加了“0”,这导致两列捕获相同的数据;示例:
df4 = pd.DataFrame({'MSG235': [1,0,1,0,0], 'MSG0235': [0,0,0,1,1]})
df4
MSG0235 MSG235
0 1
0 0
0 1
1 0
1 0
如何组合这些列,如果其中一个(或两个)等于 1,则结果将为 1,如果两个且仅两个都为 0,则结果将为 0?
我正在寻找这样的东西:
MSG235
1
0
1
1
1
我已经尝试过:
df4.rename(columns = {'MSG0235': 'MSG235'}, inplace = True)
def col_join(x):
return ''.join(x[x.notnull()].astype(str))
df4.groupby(level = 0, axis = 1).apply(lambda x: x.apply(col_join, axis = 1))
结果是:
MSG235
01
00
01
10
10
最佳答案
你可以试试
df4['MSG235'] = (df4.any(1) == 1).astype(int)
df4.drop('MSG0235', axis = 1, inplace = True)
MSG235
0 1
1 0
2 1
3 1
4 1
关于python-3.x - 将两个 pandas 列与基于值组合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47211289/