简体   繁体   English

从字典创建 dataframe

[英]create dataframe from dictionary

In order to iterate a list through a function, I used the following code:为了通过 function 迭代列表,我使用了以下代码:

tot = {}

for i in list:
    tot["tot{0}".format(i)] = stateagg(i) #previously defined function

The output of this is a pandas dictionary, I was wondering if there is a way to output to a dataframe or a way to convert this back to a dataframe. The output of this is a pandas dictionary, I was wondering if there is a way to output to a dataframe or a way to convert this back to a dataframe.

I have tried我努力了

pd.Dataframe.from_dict(tot, orient = 'index')

which results in the following error:这会导致以下错误:

ValueError: If using all scalar values, you must pass an index

Any help much appreciated.非常感谢任何帮助。

Edit: apologies I should've been clearer, the function pulls values out of a dataframe to create the dictionary, the data used isn't in list format.编辑:道歉我应该更清楚,function 从 dataframe 中提取值来创建字典,使用的数据不是列表格式。 The list is used to pull the values out and aggregate data based on the list.该列表用于提取值并基于列表聚合数据。

To create a dataframe from list, you can try something as follows要从列表中创建 dataframe,您可以尝试以下操作

df = pd.DataFrame(my_list.items(), columns={"A", "B"})

For example例如

my_list = {"Math":25, "Diana":22, "Jhon":30}
df = pd.DataFrame(my_list.items(), columns={"Name", "Age"})
df
    Name    Age
0   Math    25
1   Diana   22
2   Jhon    30

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM