简体   繁体   English

Append pandas dataframe 与字典使用for循环

[英]Append pandas dataframe with dictionary using for loop

I have the following dictionary and I want to add these in to a pandas dataframe:我有以下字典,我想将它们添加到 pandas dataframe 中:

crimes1 = {'SOUTHERN': 28445,
 'NORTHERN': 20100,
 'MISSION': 19503}

I create the blank dataframe with the column names I want:我用我想要的列名创建了空白 dataframe :

column_names = ['Neighborhood', 'Count']
crimes2 = pd.DataFrame(columns=column_names)

Next I want to append the dataframe with my dictionary containing the keys and values above using a for loop:接下来我想 append dataframe 与我的字典包含上面使用 for 循环的键和值:

for i, x in crimes1:
    crimes2 = crimes2.append({'Neighborhood': i}, {'Count': x}, ignore_index=True)

The error I get is ValueError: too many values to unpack (expected 2)我得到的错误是ValueError: too many values to unpack (expected 2)

I can populate only one column when I do it separately but can't seem to get both in to the one dataframe.当我单独执行时,我只能填充一列,但似乎无法同时进入 dataframe。 Any ideas on how to get this to work using the for loop above?关于如何使用上面的 for 循环使其工作的任何想法?

You are getting ValueError because you are not calling crimes1.items() which is require to iterate over the key, value pairs of dictionary.您收到ValueError是因为您没有调用crimes1.items() ,这需要遍历字典的键、值对。 Simply, Use:简单地说,使用:

for i, x in crimes1.items():
    crimes2 = crimes2.append({'Neighborhood': i, 'Count': x}, ignore_index=True)

Result:结果:

# print(crimes2)
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503

You can use the map function您可以使用map function

crimes2 = pd.DataFrame(map(list, crimes1.items()))

crimes2.columns = ['Neighborhood', 'Count']

You can try this.你可以试试这个。

crimes2 = pd.DataFrame(crimes1.items(), columns=['Neighborhood', 'Count'])
  Neighborhood  Count
0     SOUTHERN  28445
1     NORTHERN  20100
2      MISSION  19503

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

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