[英]Dictionary to Pandas Dataframe Python
I have two python dictionaries.我有两个 python 字典。
Sample:样本:
{
'hello' : 10
'phone' : 12
'sky' : 13
}
{
'hello' : 8
'phone' :15
'red' :4
}
This is the dictionary of counts of words in books 'book1' and 'book2' respectively.这是分别在书籍“book1”和“book2”中的单词计数字典。
How can I generate a pd dataframe, which looks like this:如何生成一个 pd dataframe,如下所示:
hello phone sky red
book1 10 12 13 NaN
book2 8 15 NaN 4
I have tried:我努力了:
pd.DataFrame([words,counts])
It generated:它产生了:
hello phone sky red
0 10 12 13 NaN
1 8 15 NaN 4
How can I genrate a required output?如何生成所需的 output?
You need this:你需要这个:
pd.DataFrame([words, counts], index=['books1', 'books2'])
Output: Output:
hello phone red sky
books1 10 12 NaN 13.0
books2 8 15 4.0 NaN
try the below code,hope this helps试试下面的代码,希望对你有帮助
dict1 = {
'hello' : 10,
'phone' : 12,
'sky' : 13
}
dict2 = {
'hello' : 8,
'phone' :15,
'red' :4
}
import pandas as pd
df = pd.DataFrame([dict1,dict2], index=['book1','book2'])
print(df)
Ouput will be:输出将是:
hello phone sky red
book1 10 12 13.0 NaN
book2 8 15 NaN 4.0
Use df.set_index(['book1', 'book2'])
.使用
df.set_index(['book1', 'book2'])
。 See the docs here: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.html请参阅此处的文档: https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.set_index.ZFC35FDC70D5FC69D2539883A8E2C7
Assuming you have a list of dictionaries, you could do something like this:假设您有一个字典列表,您可以执行以下操作:
import pandas as pd
from itertools import chain
data = [{
'hello': 10,
'phone': 12,
'sky': 13,
},
{
'hello': 8,
'phone': 15,
'red': 4
}]
df = pd.DataFrame(data=data, columns=set(chain.from_iterable(d.keys() for d in data)))
print(df)
Output Output
sky phone hello red
0 13.0 12 10 NaN
1 NaN 15 8 4.0
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.