python - 如何根据字典列表中的特定值在单独的 Dataframe 列中创建列表?

标签 python pandas dataframe list-comprehension apply

我有一个名为 'new_api_df' 的数据框,其中包含一个名为 new_api_df['Categories'] 的列,其中包含字典列表:

[{'CallId': 22143866, 'BucketId': 1953, 'SectionId': 1256, 'BucketFullName': 'Categories.Filters.No Sale Made', 'Weight': 1.0}
, {'CallId': 22143866, 'BucketId': 2016, 'SectionId': 1255, 'BucketFullName': 'Categories.Imported.Objections', 'Weight': 3.0}
, {'CallId': 22143866, 'BucketId': 2017, 'SectionId': 1255, 'BucketFullName': 'Categories.Imported.Touting Benefits', 'Weight': 1.0}
]

我想获取每个“BucketFullName”并将这些值放入单独列 new_api_df['category_list'] 的列表中,如下所示:

['Categories.Filters.No Sale Made'、'Categories.Imported.Objections'、Categories.Imported.Touting Benefits']

我尝试过使用列表理解,如下所示:

new_api_df['category_list'] =[item['BucketFullName'] 表示 new_api_df['Categories'] 表示字典中的项目]

但出现错误:ValueError:值的长度与索引的长度不匹配

我还尝试过应用和列表理解: new_api_df['category_list'] = new_api_df['Categories'].apply([item['BucketFullName'] fordictionary in new_api_df['Categories'] for item indictionary])

但我收到以下错误: AttributeError:“Categories.Filters.No Sale Made”不是“Series”对象的有效函数

我也尝试过:new_api_df['category_list'] = df['Categories'].apply(lambda x: x['BucketFullName'])

但出现错误:TypeError:列表索引必须是整数或切片,而不是 str

new_api_df 切片:

new_api_df.loc[0]:

Contact            {'Id': 22143866, 'Type': 'Call', 'WavPath': '\...
RecordInfo         {'Id': 22143866, 'RowNumber': 1, 'TotalRowCoun...
Measures           {'ID': 22143866, 'TotalHoldCount': 0, 'Agitati...
Others             {'ConfidenceAverage': 69, 'SequenceID': None, ...
Sections           [{'CallId': 22143866, 'SectionId': 1041, 'Sect...
Categories         [{'CallId': 22143866, 'BucketId': 1953, 'Secti...
Scores             [{'CallId': 22143866, 'ScoreId': 399, 'ScoreNa...
ScoreComponents    [{'CallId': 22143866, 'ScoreComponentId': 4497...```

最佳答案

我想你想要

df=pd.DataFrame({'Categories':[{'CallId': 22143866, 'BucketId': 1953, 'SectionId': 1256, 'BucketFullName': 'Categories.Filters.No Sale Made', 'Weight': 1.0}
, {'CallId': 22143866, 'BucketId': 2016, 'SectionId': 1255, 'BucketFullName': 'Categories.Imported.Objections', 'Weight': 3.0}
, {'CallId': 22143866, 'BucketId': 2017, 'SectionId': 1255, 'BucketFullName': 'Categories.Imported.Touting Benefits', 'Weight': 1.0}
]})

df['category_list']=df['Categories'].apply(lambda x: x[0]['BucketFullName'])
print(df)

#                                          Categories  \
#0  {'CallId': 22143866, 'BucketId': 1953, 'Sectio...   
#1  {'CallId': 22143866, 'BucketId': 2016, 'Sectio...   
#2  {'CallId': 22143866, 'BucketId': 2017, 'Sectio...   
#
#                          category_list  
#0       Categories.Filters.No Sale Made  
#1        Categories.Imported.Objections  
#2  Categories.Imported.Touting Benefits  

更新

请注意,这会为每个单元格创建一个列表。

df['category_list']=df['Categories'].apply(lambda x: [m_dict['BucketFullName'] for m_dict in x])

然后你可以使用DataFrame.explode

df = df.explode('category_list')
#(df['Categories'].apply(lambda x: [m_dict['BucketFullName'] for m_dict in x])                                                             
#                  .explode()) #check the explode serie

关于python - 如何根据字典列表中的特定值在单独的 Dataframe 列中创建列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59757541/

相关文章:

python - 获取 pandas 数据框中每个单元格的索引名称和列名称

python - 每次在 python 中使用 subprocess.call 发送 linux 电子邮件时都会得到一个空体

python - 如何使用 TensorFlow 将值列表放入张量的给定位置

python - Word2Vec:使用 Gensim 上传预先训练的 word2vec 文件时收到错误

python - float object has no attribute __getitem__ [Looked elsewhere but haven't been able to find anything applicable]

python - Pandas 获取类别到整数值的映射

python - 如何只为pandas中IsB列不为空的记录设置IsA?

python - 将 pandas DataFrame 中每一行的最后一个非零值转换为 0

python - pandas dataframe 删除 groupby 中超过 n 行的组

Python pandas 通过检查值是否更改然后之前的值进行分组