在 pandas 数据框单元格中插入列表 [英] Insert list in pandas dataframe cell

查看:96
本文介绍了在 pandas 数据框单元格中插入列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一本字典,其中每个键都有一个值列表。
与每个键关联的列表的长度不同。
我想将字典转换为带有两列键和值的pandas数据框。每行在键列中都有一个字典键,在值列中有与之相关的值列表。数据框如下所示:

I have a dictionary where each key has a list of values. Length of the list associated with each key is different. I want to convert the dictionary into a pandas dataframe with two columns 'Key' and 'Values'. Each row having one dictionary key in the 'Key' column and the list of values associated with it in 'Values' column. The dataframe will look as follows:

mapping_dict = {'A':['a', 'b', 'c', 'd'], 'B':['aa', 'bb', 'cc']}

df = 
    Key   Value
0   A     ['a', 'b', 'c', 'd']
1   B     ['aa', 'bb', 'cc']

我尝试使用了此处提供的答案,根据我的用例进行了修改。
,但没有输出所需答案。

I tried using the answer provided here by modifying it as per my use case. But it didn't output the required answer.

推荐答案

使用 pd.Series 构造函数中,因为字典值的大小不相等,所以 set_axis 添加列名,即

Use pd.Series inside constructor, since dict values sizes are not equal, then set_axis to add column names i.e

mapping_dict = {'A':['a', 'b', 'c', 'd'], 'B':['aa', 'bb', 'cc']}

df = pd.DataFrame(pd.Series(mapping_dict).reset_index()).set_axis(['Key','Value'],1,inplace=False)

  Key         Value
0   A  [a, b, c, d]
1   B  [aa, bb, cc]

选项2,将字典项转换为列表,然后将其传递给构造函数:

Option 2 , convert the dict items to list then pass it to constructor:

df = pd.DataFrame(list(mapping_dict.items()),columns=['Key','Value'])

这篇关于在 pandas 数据框单元格中插入列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆