【问题标题】:Pandas dataframe manipulating with long string column to 2 columns dynamicallyPandas 数据框将长字符串列动态操作为 2 列
【发布时间】:2021-09-13 11:56:14
【问题描述】:

我有数据框:

id greetingsname
1 hello+peter|goodbye+john
2 hi+cheff|gutentag+rudolf|goodafternoon+Alex

我想要

id greeting name
1 hello peter
1 goodbye john
2 hi cheff
2 gutentag rudolf
2 goodafternoon Alex

我不知道,如何动态拆分列 greetingsname,以获得我想要的,因为列 greetingsname 具有不同的字符串长度。但是分隔符分布保持不变greeting DELIMETER(+) name DELIMETER(|) greeting DELIMETER(+) name

从这个意义上说,它可以有不同的长度(几个名字和问候语,在另一列中有不同数量的名字和问候语)

谢谢

【问题讨论】:

    标签: python pandas jupyter-notebook jupyter-lab


    【解决方案1】:

    我们可以试试extractall

    df.set_index('id')['greetingsname']\
      .str.extractall(r'(?P<greeting>[^+|]+)\+(?P<name>[^|]+)').droplevel(1)
    

             greeting    name
    id                       
    1           hello   peter
    1         goodbye    john
    2              hi   cheff
    2        gutentag  rudolf
    2   goodafternoon    Alex
    

    【讨论】:

    • 你能解释一下这个正则表达式是如何工作的吗?
    • @tayfunyiğit 当然。我会用正则表达式的解释来编辑答案。
    【解决方案2】:

    您可以为此使用爆炸:

    df['greetingsname']=df['greetingsname'].apply(lambda x: x.split('|'))
    
    res=df.explode('greetingsname')
    
    print(res)
    
       id       greetingsname
    0   1         hello+peter
    0   1        goodbye+john
    1   2            hi+cheff
    1   2     gutentag+rudolf
    1   2  goodafternoon+Alex
    
    res[['greeting', 'name']] = res['greetingsname'].str.split('+', expand=True)
    
    del res['greetingsname']
    
    res.reset_index(drop=True, inplace=True)
    
    print(res)
    
       id       greeting    name
    0   1          hello   peter
    1   1        goodbye    john
    2   2             hi   cheff
    3   2       gutentag  rudolf
    4   2  goodafternoon    Alex
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-11-25
      • 1970-01-01
      • 2015-05-18
      • 1970-01-01
      • 2012-10-28
      相关资源
      最近更新 更多