python-3.x - 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.
解决方案
.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()}
推荐阅读
- javascript - 使用 Laravel 提交带有文本字段值和图像的 AJAX 请求
- python - 无法加载 sklearn.datasets 导入 load_iris
- android - 列表重复从一个片段导航并在 NavigationComponents 中返回
- apache-spark - 并行运行多个 Spark 应用程序
- python - 我发现在 python 中为 numpy 数组编制索引很奇怪
- c - 读取字符串时scanf未给出预期结果
- sensenet - SenseNet 新创建的内容在查询时不显示
- for-loop - 有没有办法在 Google Script 中加速这个 for 循环?
- angular - 在Angular 6中的表单中添加动态输入文本时出现索引问题
- github - 如何在 Github Actions Job 期间用代码中的 Secret 替换 API 密钥?