首页 > 解决方案 > GeoPandas dataFrame using iterrows() to fill a dictionary with column data

问题描述

I am using pandas DataFrame to make a nested dictionary with a column that contains names. Each dictionary element is a nested dictionary and each nested dictionary's key is a name from the DataFrame column.

I am using this line to fill the dictionary:

for row, name in map_datafile.iterrows():         
    material_count[name._get_value(label='NAME')] = {}

For some reason, the resulting dictionary contains only 579 of the 586 names contained in the DataFrame. For this reason, when I go to add a column with new data that I calculated from this dictionary, I get this error:

ValueError: Length of values does not match length of index

Indicating that the length of the values to be inserted into the DataFrame is different than the DataFrame.

Am I filling the dictionary incorrectly? Any advice on this issue would be great, I am new to DataFrames.

标签: python-3.xdataframedictionarygeopandas

解决方案


.iterrows()返回索引,然后返回行。
此外,您可以使用不同的语法来访问该值,而不是调用._get_value().
所以你可以这样做:

for idx, row in map_datafile.iterrows():         
    material_count[row['NAME']] = {}

您也可以这样做(可能更快):

material_count = {k:{} for k in map_datafile['NAME'].to_list()} 

推荐阅读