如果数据框中的行以关键字开头,则将其与上面的行连接

If row in dataframe starts with keyword, concat it with the row above

我有一个类似的问题,但是一直没能攻破

我有一个结构如下的 DataFrame:

0 inner join xx
1 on xx
2 and xx
3 and yy
4 and aa
5 inner join zz

我试图将以 'and' 开头的行附加到上一行,结果如下所示:

0 inner join xx
1 on xx and xx and yy and aa
2 inner join zz

稍后,我将用 'on' 关键字做同样的事情。

这是我目前拥有的代码。它有效,但只附加一次。给我留下一个额外的 'and' 关键字:

for row in df:
     s = df['join'].shift(-1)
     m = s.str.startswith('and', na=False)
     df.loc[m, 'join'] += (' ' + s[m])

您可以使用简单的 for 循环解决此问题:

result = []
for j in df['join']:
    if j.startswith('and') and len(result) > 0:
        result[-1] += ' ' + j
    else:
        result.append(j)

您可以使用groupby+apply:

(df.groupby((~df['join'].str.startswith('and ')).cumsum())
   ['join'].apply(' '.join)
)

输出:

join
1                 inner join xx
2    on xx and xx and yy and aa
3                 inner join zz
Name: join, dtype: object