首页 > 解决方案 > Collapsing rows in a Dataframe into one specific row to fill missing values?

问题描述

I want to collapse values in all rows into the first (or specified) row

The dataframe looks like this:

id     column1     column2     column3
A                  15          
B      13  
C                              10

I want it to look like this:

id     column1     column2     column3
A      13            15        10  

Apologies if my formatting sucks, this is my first submission.

标签: pythondataframemerge

解决方案


一个技巧是使用GroupBy.first默认忽略 NA 值。

df[df.ne('')].groupby(np.zeros(len(df))).first()

另一个选项是''.join在每一列中使用,因为这些空槽中有空字符串。

df.astype(str).apply(''.join).to_frame().T

    id  column1  column2  column3
0.0  A     13.0     15.0     10.0

推荐阅读