【问题标题】:How to place the list of dictionary into columns of Dataframe?如何将字典列表放入 Dataframe 的列中?
【发布时间】:2021-04-29 08:04:26
【问题描述】:

我有一列有字典列表,列表的长度是不同的。如下图:

 id             Categories
    
    1      [  { "S" : "Restaurants" },  { "S" : "Drinks" },  { "S" : "Catch Up With Friends" }]
    2      [  { "S" : "Drinks" },  { "S" : "Rooftop" },  { "S" : "Outside" }]
    3      [  { "S" : "Drinks" },  { "S" : "Rooftop" }]
    4      [  { "S" : "Drinks" },  { "S" : "Nights" }, {"S":"Restaurant"}]
    .
    .
    .

我想将字典列表放入 DataFrame 的单独列中。 输出应如下所示:

 Category 1     Category 2    Category 3  ....

Category 1 will represents (S:Restaurants)
Category 2 will represents (S:Drinks)
Category 3 will represents (S:Nights) etc ..

这怎么可能,如果有人提出比这更好的解决方案,也将不胜感激。我的目标只是解压缩字典列表并将作为列放入数据框中。如果是整数形式就好了。

【问题讨论】:

    标签: python pandas list dataframe dictionary


    【解决方案1】:

    试试这个:

    df = pd.DataFrame({"categories":[[  { "S" : "Restaurants" },  { "S" : "Drinks" },  { "S" : "Catch Up With Friends" }],
                       [  { "S" : "Drinks" },  { "S" : "Rooftop" },  { "S" : "Outside" }],
                       [  { "S" : "Drinks" },  { "S" : "Rooftop" }],
                       [  { "S" : "Drinks" },  { "S" : "Nights" }, {"S":"Restaurant"}]]})
    
    df = pd.DataFrame([i for i in df.categories])
    print(df)
    

    输出:

    【讨论】:

    • 我在我的帖子中提到,标题的长度不是固定的,它是多种多样的
    • 您只需删除列属性即可获得所需的结果。我已经编辑了帖子。
    • 没有想要的结果,它只给出了单列的输出
    • 请告诉我您遇到的错误或问题?
    • 我有现有的类别列(字典列表),您编写数据框的代码。
    【解决方案2】:

    对我来说,这看起来像是 pandas.DataFrame.apply 的 expand 模式的任务,简单示例:

    import pandas as pd
    df = pd.DataFrame({'x':[[{'A':1},{'B':2},{'C':3}],[{'D':4},{'E':5},{'F':6}]]})
    df.apply(lambda x:x, axis=1, result_type='expand')
    df = df.apply(lambda x:x[0], axis=1, result_type='expand')
    print(df)
    

    输出

              0         1         2
    0  {'A': 1}  {'B': 2}  {'C': 3}
    1  {'D': 4}  {'E': 5}  {'F': 6}
    

    此解决方案假定您原来的 pandas.DataFrame 正好有 1 列。

    【讨论】:

    • 如果我有几列怎么办,因为也存在多列。我
    • 如果您可以通过编写代码来编辑帖子,这对我有好处
    猜你喜欢
    • 2019-01-05
    • 1970-01-01
    • 2023-03-19
    • 1970-01-01
    • 1970-01-01
    • 2014-09-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多