【问题标题】:How to Convert String Dictionary to Dictionary and the split into separate columns如何将字符串字典转换为字典并拆分为单独的列
【发布时间】:2021-05-14 06:55:38
【问题描述】:

我有一个单列 pandas 数据框,看起来每个字典当前都是一个字符串。我想将 pandas 中的每个项目转换为字典,然后将其拆分为单独的列。

当前外观

0         {'Owl': '8109284', 'county': '27'}
1         {'Kid': '298049', 'county': '28'}
2         {'Tree': '190849', 'county': '29'}
3         {'Garden': '9801294', 'county': '30'}
4         {'House': '108094', 'county': '31'}

End Look

           Item     Count      County   County Number
0         'Owl'    '8109284' 'county'     '27'
1         'Kid'    '298049'  'county'     '28'
2         'Tree'   '190849'  'county'     '29'
3         'Garden' '9801294  'county'     '30'
4         'House'  '108094'  'county'     '31'


Can anyone help resolve this. I've tried a bunch of different things.

【问题讨论】:

标签: python pandas string dataframe dictionary


【解决方案1】:

您可以使用literal_eval()string 中获取dict 对象。之后使用dictionary 上的items() 方法获取项目。最后,构建数据框。

import ast
import pandas as pd

d = [[0,         "{'Owl': '8109284', 'county': '27'}"],
[1,         "{'Kid': '298049', 'county': '28'}"],
[2,         "{'Tree': '190849', 'county': '29'}"],
[3,         "{'Garden': '9801294', 'county': '30'}"],
[4,         "{'House': '108094', 'county': '31'}"]]

df = pd.DataFrame(d, columns=['a', 'b'])


pd.DataFrame(df['b'].apply(lambda x: [j for i in ast.literal_eval(x).items() for j in i]).to_list(), 
             columns=['Item', 'Count', 'County', 'County Number'])
        Item    Count   County  County Number
0       Owl     8109284 county  27
1       Kid     298049  county  28
2       Tree    190849  county  29
3       Garden  9801294 county  30
4       House   108094  county  31

【讨论】:

    【解决方案2】:

    如果您的 dicts 格式相同(2 个键,2 个值),您可以使用 apply 功能。 'data' 是您的 dict 列:

    df['Item']=df.data.apply(lambda x: list(eval(x).keys())[0])
    df['Count']=df.data.apply(lambda x: list(eval(x).values())[0])
    df['County']=df.data.apply(lambda x: list(eval(x).keys())[1])
    df['County Number']=df.data.apply(lambda x: list(eval(x).values())[0])
    
    del df['data']
    

    输出

        Item    Count  County County Number
    0  Owl     8109284  county  8109284
    1  Kid     298049   county  298049
    2  Tree    190849   county  190849
    3  Garden  9801294  county  9801294
    4  House   108094   county  108094
    

    【讨论】:

      猜你喜欢
      • 2020-02-08
      • 1970-01-01
      • 1970-01-01
      • 2014-06-09
      • 1970-01-01
      • 2021-09-09
      • 1970-01-01
      • 1970-01-01
      • 2015-03-10
      相关资源
      最近更新 更多