【问题标题】:Python explode strings with comma and quotesPython用逗号和引号分解字符串
【发布时间】:2021-11-26 11:34:43
【问题描述】:

我有一个具有以下设置的数据集:

id   string_to_parse
1    "a","b"
2   "a,b","c"  
3   "c"

我需要把它放进去

id   string_to_parse
1    a
1    b
2    a,b
2    c
3    c

我试过了

exploded_ = df['string_to_parse'].map(lambda x:x\
    .replace('"','')\
    .split(",")).explode()

除了速度很慢之外,它还错过了"a,b" 并将它们也拆分了。

【问题讨论】:

    标签: python pandas explode


    【解决方案1】:

    使用Series.str.stripSeries.str.split 和最后一个DataFrame.explode

    df['string_to_parse'] = df['string_to_parse'].str.strip('"').str.split('","')
    df  = df.explode('string_to_parse')
    print (df)
       id string_to_parse
    0   1               a
    0   1               b
    1   2             a,b
    1   2               c
    2   3               c
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-10-10
      • 1970-01-01
      • 2011-04-16
      • 2017-01-05
      • 2012-05-23
      相关资源
      最近更新 更多