简体   繁体   中英

Merging columns in the same dataframe in pandas

Is there a method/inbuilt function in pandas that allows for multiple columns to be merged into one based upon the names of the column?

eg taking these 3 columns in which each row will only have a single non-NaN value

+-------+-------+-------+
| name1 | name2 | name3 |
+-------+-------+-------+
| a     | NaN   | NaN   |
| b     | NaN   | NaN   |
| NaN   | c     | NaN   |
| NaN   | d     | NaN   |
| NaN   | NaN   | e     |
| NaN   | NaN   | f     |
+-------+-------+-------+

and creating a new column such as

+------+
| name |
+------+
| a    |
| b    |
| c    |
| d    |
| e    |
| f    |
+------+

I'm aware you could do something with 2 columns like df.fill to fill in an existing column, but is there a way to create a new, filled column as in my example?

Use bfill :

df['name'] = df.bfill(axis=1)['name1']
print(df)

# Output
  name1 name2 name3 name
0     a   NaN   NaN    a
1     b   NaN   NaN    b
2   NaN     c   NaN    c
3   NaN     d   NaN    d
4   NaN   NaN     e    e
5   NaN   NaN     f    f

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