【问题标题】:How to Split a comma separated string of dictionaries into a Pandas dataframe如何将逗号分隔的字典字符串拆分为 Pandas 数据框
【发布时间】:2017-09-10 12:54:35
【问题描述】:

我有一个这种格式的字符串:

{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}

并希望创建一个数据框,其列标签为“apple”、“oranges”、“x”,并将值放置在各自的行中。

我尝试使用此解决方案:Python convert comma separated list to pandas dataframe 以及 ast.literal_eval 将其转换为列表,然后再将其转换为数据框,但没有成功。

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    你的字符串无效json,所以需要先替换一下:

    import ast
    
    s = '{apple:"34253453",oranges:"Sweet",x:"COOL"},{apple:"34222453",oranges:"Dry",x:"WARM"},{apple:"31113453",oranges:"Bitter",x:"HOT"},{apple:"38883453",oranges:"Sweet",x:"COOL"}'
    
    ss = '[' + s.replace('{', '{"').replace(':"','":"').replace('",', '","') + ']'
    print (ss)
    
    [{"apple":"34253453","oranges":"Sweet","x":"COOL"},
     {"apple":"34222453","oranges":"Dry","x":"WARM"},
     {"apple":"31113453","oranges":"Bitter","x":"HOT"},
     {"apple":"38883453","oranges":"Sweet","x":"COOL"}]
    

    df = pd.DataFrame(ast.literal_eval(ss))
    print (df)
          apple oranges     x
    0  34253453   Sweet  COOL
    1  34222453     Dry  WARM
    2  31113453  Bitter   HOT
    3  38883453   Sweet  COOL
    

    df = pd.DataFrame(pd.io.json.loads(ss))
    print (df)
          apple oranges     x
    0  34253453   Sweet  COOL
    1  34222453     Dry  WARM
    2  31113453  Bitter   HOT
    3  38883453   Sweet  COOL
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-02-24
      • 1970-01-01
      • 1970-01-01
      • 2012-05-24
      相关资源
      最近更新 更多