如果同一行的另一列中存在 null,则将列值与上一行连接



>我有一个这样的数据框,

DF:

col1      col2       col3
 1        cat          4
nan       dog         nan 
 3        tiger         3
 2        lion          9
 nan      frog         nan
 nan     elephant      nan
我想从这个数据框创建一个数据框,该

数据框 col1 中有 nan 值,col2 值将添加到上一行值。

例如,所需的输出数据框将为:

col1     col2             col3
 1      catdog             4
 3       tiger             3
 2     lionfrogelephant    9

如何使用熊猫来做到这一点?

使用正向填充缺失值并聚合join

cols = ['col1','col3']
df[cols] = df[cols].ffill()
df = df.groupby(cols)['col2'].apply(''.join).reset_index()
print (df)
   col1  col3              col2
0   1.0   4.0            catdog
1   2.0   9.0  lionfrogelephant
2   3.0   3.0             tiger

或者,如有必要,向前填充所有列中的缺失值:

df = df.ffill().groupby(['col1','col3'])['col2'].apply(''.join).reset_index()
print (df)
   col1  col3              col2
0   1.0   4.0            catdog
1   2.0   9.0  lionfrogelephant
2   3.0   3.0             tiger

最新更新