简体   繁体   中英

Concatenate two columns in pandas data frame

My data frame looks like -

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

I want my data frame looks like -

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

I have done -

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=' ')

But got this error -

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

and no missing or null value is present.

You just need to change the type of the values you take from the 'value' column for concatenation. Concatenation works only on suitable data types. In your code it's string + float which will not work. This will help you:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM