我正在以这种方式在Python pandas
中创建一个字符串表达式
df['ABC'] = (df['A']
+ ' + ' + df['B']
+ ' + ' + df['C'])
但是,pandas
会返回此错误
TypeError: cannot concatenate 'str' and 'float' objects
对于少数列,数据框具有NaN
,并且字符串连接在这些情况下失败。我如何编写一个语句来实现如下所示的连接测试用例。看起来我们必须在上面的表达式中添加一个ifelse语句:
A B C ABC
x x
x y x + y
x y z x + y + z
答案 0 :(得分:3)
你可以这样做:
>>> join_row = lambda ts: ' + '.join(ts.dropna())
>>> df[['A', 'B', 'C']].apply(join_row, axis=1)
0 x
1 x + y
2 x + y + z
dtype: object
只有在数据框中有其他列时才需要 [['A', 'B', 'C']]
。