简体   繁体   中英

Pandas merge multiple string and Nan columns into one

    Chat     A         B       C      D ......  X
0   I'm     groot     Nan     Nan    Nan       Nan
1   I        am      rocket   Nan    Nan       Nan

I have a df with multiple columns contain Strings in it and some of them are Nan I want to merge them all into one column and drop the rest. The result should be something like this:

     Chat
0   I'm groot
1   I am rocket

fillna + str.join

Fill, join, and cleanup:

df = df.fillna('').agg(' '.join, 1).str.replace('\s{2,}', ' ').str.strip()
df
          Chat
0    I'm groot
1  I am rocket

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