如何使用 python 合并 df 行?

How to combine rows of df using python?

我正在尝试连接包含字符串的数据框的行。我想检查该行是否包含 NaN ,如果是,则从该行中删除 NaN 并将其余部分与该行上方的连接起来。最后删除包含 NaN 的行。

这是我的示例数据:

df=[["d","t","u","y","e"],["d",np.nan,np.nan,np.nan,"o"],["y","p","p","w","r"]]
df=pd.DataFrame(df)
print(df)
0    1    2    3  4
d   t    u    y   e
d  NaN  NaN  NaN  o
y    p    p    w  r

我希望输出如下所示。

   0    1    2    3   4
   dd   t    u    y  eo   
   y    p    p    w   r

这是我的试用版,但没有成功。

for i in range(len(df)):
for j in range(len(df.iloc[1,])):
    if(pd.isnull(df.iloc[i,j])==True):
        df.concat(df.iloc[i,j],df.iloc[i-1,j])
        df.dropna(df.iloc[:,i])

我是 Python 的新手,谁能帮我解决这个问题。

想法是创建分组助手Series

因此,首先为所有至少有一个 NaN 的行创建掩码 DataFrame.isna with DataFrame.any, create Series by constructor, replace non match values to NaNs by Series.where,然后用 limit=1 填充上面相同组的缺失值,只替换上面的一行。

最后将所有缺失值替换为空值,分组聚合join

m = df.isna().any(axis=1)
s = pd.Series(np.arange(len(m)), index=df.index)
g = s.where(m).bfill(limit=1).fillna(s)

df = df.fillna('').groupby(g).agg(''.join).reset_index(drop=True)
print (df)
    0  1  2  3   4
0  dd  t  u  y  eo
1   y  p  p  w   r