从字典中创建 Python DataFrame,其中键是列名,值是行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25318639/
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
Create Python DataFrame from dictionary where keys are the column names and values form the row
提问by user3433489
I am familiar with python but new to panda DataFrames. I have a dictionary like this:
我熟悉 python 但不熟悉 Panda DataFrames。我有一本这样的字典:
a={'b':100,'c':300}
And I would like to convert it to a DataFrame, where b and c are the column names, and the first row is 100,300 (100 is underneath b and 300 is underneath c). I would like a solution that can be generalized to a much longer dictionary, with many more items. Thank you!
我想将其转换为 DataFrame,其中 b 和 c 是列名,第一行是 100,300(100 在 b 下方,300 在 c 下方)。我想要一个可以推广到更长字典的解决方案,其中包含更多项目。谢谢!
采纳答案by iayork
Pass the values as a list:
将值作为列表传递:
a={'b':[100,],'c':[300,]}
pd.DataFrame(a)
b c
0 100 300
Or if for some reason you don't want to use a list, include an index:
或者,如果由于某种原因您不想使用列表,请包含一个索引:
a={'b':100,'c':300}
pd.DataFrame(a, index=['i',])
b c
i 100 300
回答by Liam Foley
Use lists as the values in the dictionary.
使用列表作为字典中的值。
import pandas as pd
a = {'b':[100,200],'c':[300,400]}
b = pd.DataFrame(a)
In [4]: b
Out[4]:
b c
0 100 300
1 200 400

