1 回答
TA贡献1865条经验 获得超7个赞
想法是将key列转换为掩码,然后用空字符串替换不匹配DataFrame.where并求和join:
c = ['A','B','C','D','E']
L = [list(str(x)) for x in df['key']]
m = pd.DataFrame(L, columns=c, index=df.index).fillna(0).astype(int).astype(bool)
print (m)
A B C D E
0 True False True True True
1 True False True True True
2 True True False True False
3 True False True False False
4 True True False False False
5 True False True True True
df['key_val'] = df[c].where(m, '').astype(str).sum(axis=1)
print (df)
A B C D E key key_val
0 test Z 10.0 a a 10111 test10.0aa
1 test A 10.0 a a 10111 test10.0aa
2 test x 2.0 a b 11010 testxa
3 test 5 12.0 b b 10100 test12.0
4 test x 5.0 c b 11000 testx
5 test 2 14.0 g c 10111 test14.0gc
添加回答
举报