Python 如何将字典列表放入Dataframe的列中?

Python 如何将字典列表放入Dataframe的列中?,python,pandas,list,dataframe,dictionary,Python,Pandas,List,Dataframe,Dictionary,我有一列字典列表,列表的长度是不同的。如下图所示: id Categories 1 [ { "S" : "Restaurants" }, { "S" : "Drinks" }, { "S" : "Catch Up With Friends" }] 2 [ { "S" : &quo

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

 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 ..
如果有人提出比这更好的解决方案,那怎么可能呢?我的目标就是将字典列表解包,并将其作为一列放到dataframe中。如果是整数形式,那就好了。

试试这个:

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)
输出:


对我来说,这看起来像是“扩展”模式的任务,简单示例:

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
正好有一列。

我在帖子中提到,标题的长度不是固定的,而是可变的。您只需删除column属性即可获得所需的结果。我编辑了这篇文章。没有期望的结果,它只给出了单列的输出。请告诉我您面临的错误或问题?我有现有的类别列(字典列表),您为数据框编写代码。如果我有多个列,怎么办,因为也有多个列。I@Anwar从您的
pandas.DataFrame
创建单列
pandas.DataFrame
,按照回答中的说明进行操作,在索引模式下生成原始
pandas.DataFrame
。如果您可以通过编写代码编辑文章,这将对我有益