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



我有一个类似的问题,但是我没有能够突破它。

我有一个这样结构的DataFrame:

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

我试图将以'和'开头的行附加到前一行,导致看起来像这样的东西:

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])

您可以使用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

您可以使用一个简单的for循环来解决这个问题:

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

相关内容

最新更新