【问题标题】:Combine multiple row into single row if index are sequentially如果索引是顺序的,将多行合并为单行
【发布时间】:2021-07-06 14:46:45
【问题描述】:

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

所以,我有一个像这样的数据框:

    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
 

任何人都可以通过这个吗?

【问题讨论】:

  • 您使用索引值或仅位置定义顺序?假设Parrot 是小写的parrot,它会和Bulldog hatcet 连接吗?

标签: python pandas dataframe lowercase


【解决方案1】:

我们可以通过首先使用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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-23
    • 1970-01-01
    • 1970-01-01
    • 2018-02-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多