在Pandas数据框中连接两列

4

我的数据框如下所示 -

state        msg              value
aa          a,b,r              .22
bb          m,b,r             1.43
cc          a,b,q              .33
dd          h,h,f              .25

我希望我的数据框看起来像 -
state        msg              value      text
aa          a,b,r              .22      a,b,r .22
bb          m,b,r             1.43      m,b,r 1.43
cc          a,b,q              .33      a,b,q .33
dd          h,h,f              .25      h,h,f .25

我已经完成了 -

df.info()

 #   Column        Non-Null Count  Dtype 
---  ------        --------------  ----- 
 0   state         6925 non-null   object
 1   msg           6925 non-null   object
 2   value         6925 non-null   object

df['text'] = df['state'].astype(str).str.cat(df['value'], sep=' ')

但是遇到了这个错误 -

TypeError: Concatenation requires list-likes containing only strings (or missing values). Offending values found in column mixed.

并且不存在缺失或空值。


1
df['msg'].astype(str).str.cat(df['value'].astype(str), sep=' ') - Shubham Sharma
1个回答

8

你只需要更改从“值”列中获取的值的类型以进行串联。串联仅适用于适当的数据类型。在您的代码中,它是字符串 + 浮点数,这将不起作用。 以下内容可能对你有所帮助:

df['text'] = df['state'].astype(str).str.cat(df['value'].astype(str), sep=' ')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接