如果索引是顺序的,则将多行合并为单行
Combine multiple row into single row if index are sequentially
看起来我想将动物列中的多行转换为单行。但是,只有满足序号和小写字母才有条件。之后,它重新启动索引成为 sequent
所以,我有一个像这样的数据框:
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
任何人都可以通过这个吗?
我们可以通过首先使用 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
看起来我想将动物列中的多行转换为单行。但是,只有满足序号和小写字母才有条件。之后,它重新启动索引成为 sequent
所以,我有一个像这样的数据框:
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
任何人都可以通过这个吗?
我们可以通过首先使用 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