如果索引按顺序排列,则将多行合并为单行

2024-06-12 01:27:09 发布

您现在位置:Python中文网/ 问答频道 /正文

看起来我想在animal列中将多行转换为单行。但是,只有当它们满足序列号和小写字母时,它才是有条件的。之后,它会重新启动一个索引,使其成为连续索引

因此,我有一个数据帧,如:

    Animal 
 0  Bulldog
 1  hatcet 
 3  Parrot 
 7  Carrot 
 8  Jack Dog
 9  Kanggaroo
 10 helma  

我想达到的目标是

    Animal 
 0  Bulldog hatcet 
 1  Parrot
 2  Carrot 
 3  Jack Dog
 4  Kanggaroo helma
 

有人能通过吗


Tags: 条件中将序列号parrotjackdog单行animal
1条回答
网友
1楼 · 发布于 2024-06-12 01:27:09

我们可以通过首先使用str.contains创建一个布尔掩码,然后对掩码进行累积和来识别顺序块。然后将这些顺序块上的列Animal分组,并使用join进行聚合

b = df['Animal'].str.contains(r'^[A-Z]').cumsum()
df[['Animal']].groupby(b, as_index=False).agg(' '.join)

            Animal
0   Bulldog hatcet
1           Parrot
2           Carrot
3         Jack Dog
4  Kanggaroo helma

相关问题 更多 >