【问题标题】:Reshape Pandas dataframe by specific string通过特定字符串重塑 Pandas 数据框
【发布时间】:2018-11-09 11:36:00
【问题描述】:

我有一个如下所示的 csv 数据集:

###12345
LABEL     text
LABEL     text
###12213
LABEL     text
LABEL     text

我想把它变成那个形状

12345 LABEL    text
12345 LABEL    text
12213 LABEL    text

我的第一个方法是过滤掉这样的行

#df['label'].str.contains("###", na=False) 

但没有成功重新排列为索引。

你能帮我解决这个问题吗? 谢谢!

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    用途:

    print (df)
                label
    0        ###12345
    1  LABEL     text
    2  LABEL     text
    3        ###12213
    4  LABEL     text
    5  LABEL     text
    

    #boolean mask
    m = df['label'].str.contains("###", na=False) 
    #helper column with repalce non ### values to NaNs and repalce it by last non NaN value
    df['new'] = df['label'].where(m).ffill()
    #remove rows with same values
    df = df[df['label'] != df['new']].copy()
    #extract new column and add to original
    df['label'] = df.pop('new').str.lstrip('#') + ' ' + df['label']
    print (df)
                      label
    1  12345 LABEL     text
    2  12345 LABEL     text
    4  12213 LABEL     text
    5  12213 LABEL     text
    

    print (df)
          label value
    0  ###12345   NaN
    1     LABEL  text
    2     LABEL  text
    3  ###12213   NaN
    4     LABEL  text
    5     LABEL  text
    
    
    m = df['label'].str.contains("###", na=False) 
    
    df['new'] = df['label'].where(m).ffill()
    df = df[df['label'] != df['new']].copy()
    df['label'] = df.pop('new').str.lstrip('#') + ' ' + df['label']
    print (df)
             label value
    1  12345 LABEL  text
    2  12345 LABEL  text
    4  12213 LABEL  text
    5  12213 LABEL  text
    

    【讨论】:

      猜你喜欢
      • 2012-12-10
      • 2020-04-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-10
      • 2017-04-23
      • 1970-01-01
      相关资源
      最近更新 更多