【问题标题】:Concatenate two columns in pandas data frame连接熊猫数据框中的两列
【发布时间】:2020-10-13 06:38:36
【问题描述】:

我的数据框看起来像 -

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.

并且不存在缺失值或空值。

【问题讨论】:

  • df['msg'].astype(str).str.cat(df['value'].astype(str), sep=' ')?

标签: python-3.x pandas scikit-learn


【解决方案1】:

您只需要更改从“值”列中获取的值的类型即可进行连接。连接仅适用于合适的数据类型。在您的代码中,它是 string + float 不起作用。 这将帮助您:

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

【讨论】:

    猜你喜欢
    • 2021-05-11
    • 1970-01-01
    • 2016-03-22
    • 2015-08-15
    • 2022-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多