【问题标题】:How to convert string representation of dictionary in Pandas DataFrame to a new columns?如何将 Pandas DataFrame 中字典的字符串表示形式转换为新列?
【发布时间】:2019-09-29 20:18:20
【问题描述】:

我在 Pandas DataFrame Column 中有一个字典的字符串表示形式,如下所示:

>>> df['the_column']
    
0 "{'a': 1., 'b': 2., 'c':3.}"
1 "{'a': 4., 'b': 5., 'c':6.}"
2 "{'a': 7., 'b': 8., 'c': 9.}"
3 "{'a': 10., 'b': 11., 'c':12.}"
    ...

我想将每个键附加到现有 DataFrame 中的列,怎么可能?

我尝试过这样的事情:

list_of_new_col = [json.loads(c) for c in df['the_column']]
# resulting list of dictionary
# convert it to pandas DataFrame
# and then concat with the existing DataFrame

但我得到了 TypeError: the JSON object must be str, bytes or bytearray, not 'float'

知道如何解决这个问题吗?

【问题讨论】:

    标签: python python-3.x pandas dataframe dictionary


    【解决方案1】:

    除了接受的答案之外,我发现这也有效

    pd.concat([df, df.the_column.apply(json.loads).apply(pd.Series)], axis=1)
    

    【讨论】:

      【解决方案2】:

      你可以试试ast

      df['the_column']=df['the_column'].apply(ast.literal_eval)
      

      【讨论】:

        猜你喜欢
        • 2010-11-02
        • 2019-03-02
        • 2021-11-10
        • 1970-01-01
        • 2020-11-20
        相关资源
        最近更新 更多