我有一个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
column:
key
在位置[0]
处为col A
,key
在位置[1]
处为col B
,依此类推...1
都用于拍摄,每个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: operands could not be broadcast together with shapes (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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句