我有一个如下所示的DataFrame
:
df
A B C D E key
0 test Z 10.0 a a 10111
1 test A 10.0 a a 10111
2 test x 2.0 a b 11010
3 test 5 12.0 b b 10100
4 test x 5.0 c b 11000
5 test 2 14.0 g c 10111
我需要得到的是根据 key
列连接所有字符串:
-
位置
key
用于col A
,key
位于位置[1 ]
用于col B
等等...- 中的每个
1
用于获取,每个0
用于跳过列
[0]
处的 结果应如下所示:
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
到目前为止我所做的 - 我创建了 key_list 列:
df['key_list'] = df['key'].apply(lambda x: list(str(x)))
df
A B C D E key key_list
0 test Z 10.0 a a 10111 [1, 0, 1, 1, 1]
1 test A 10.0 a a 10111 [1, 0, 1, 1, 1]
2 test x 2.0 a b 11010 [1, 1, 0, 1, 0]
3 test 5 12.0 b b 10100 [1, 0, 1, 0, 0]
4 test x 5.0 c b 11000 [1, 1, 0, 0, 0]
5 test 2 14.0 g c 10111 [1, 0, 1, 1, 1]
下一步我已经尝试过这个(我想乘以 1 或 0 来包含或排除字符串):
df.apply((df['A'].astype(str) * df['key_list'][0]) +
(df['B'].astype(str) * df['key_list'][1]) +
(df['C'].astype(str) * df['key_list'][2]) +
(df['D'].astype(str) * df['key_list'][3]) +
(df['E'].astype(str) * df['key_list'][4]), axis=1)
但这似乎是错误的想法:ValueError:操作数无法与形状 (6,) (5,) 一起广播
。我遵循字符串连接的常见做法,只是需要额外的步骤:
df['A'].astype(str) + df['B'].astype(str) + df['C'].astype(str) + df['D'].astype(str) + df['E'].astype(str)
最佳答案
想法是将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
关于Python:根据列与列表连接列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60165252/