pandas 在熊猫数据框单元格中插入列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/47605085/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Insert list in pandas dataframe cell
提问by Ronak Thakkar
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:
我有一本字典,其中每个键都有一个值列表。与每个键关联的列表的长度是不同的。我想将字典转换为带有两列“键”和“值”的Pandas数据框。每行在“键”列中都有一个字典键,在“值”列中具有与其关联的值列表。数据框将如下所示:
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 hereby modifying it as per my use case. But it didn't output the required answer.
我尝试使用此处提供的答案,方法是根据我的用例对其进行修改。但它没有输出所需的答案。
采纳答案by Bharath
Use pd.Series
inside constructor, since dict values sizes are not equal, then set_axis
to add column names i.e
pd.Series
在构造函数内部使用,因为字典值大小不相等,然后set_axis
添加列名,即
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]
Option 2 , convert the dict items to list then pass it to constructor:
选项 2 ,将 dict 项转换为 list 然后将其传递给构造函数:
df = pd.DataFrame(list(mapping_dict.items()),columns=['Key','Value'])
回答by Afshin Amiri
If you pass a list, pandas considers it as several rows. However, you can trick it by placing your list as the single element of an outer list as bellow:
如果您传递一个列表,pandas 会将其视为几行。但是,您可以通过将列表作为外部列表的单个元素来欺骗它,如下所示:
import pandas as pd
mapping_dict = {'A':[['a', 'b', 'c', 'd']], 'B':[['aa', 'bb', 'cc']]}
df = pd.DataFrame(mapping_dict)
df
A B
0 [a, b, c, d] [aa, bb, cc]
回答by Keith
I think you might have to update your dictionary beforehand then you can use from_dict. Update to make your dictionary to make it a list of list.
我认为您可能必须事先更新您的字典,然后才能使用from_dict。更新以使您的字典成为列表列表。
import pandas as pd
mapping_dict = {'A':['a', 'b', 'c', 'd'], 'B':['aa', 'bb', 'cc']}
updated_dict = {k: [v] for k, v in mapping_dict.items()}
df = pd.DataFrame.from_dict(updated_dict,orient='index')
If you want your exact formatting
如果你想要你的确切格式
df_formatted = df.reset_index()
df_formatted.columns = ['Key', 'Value']
print(df_formatted)
Key Value
0 B [aa, bb, cc]
1 A [a, b, c, d]
UPDATE
更新
Bharath's answer is shorter but if you still want to use from_dict then you can take part of his method to do
Bharath 的回答更短,但如果你仍然想使用 from_dict 那么你可以采用他的方法来做
df2 = pd.DataFrame.from_dict(list(mapping_dict.items()))
df2.columns = ['Key', 'Value']