【问题标题】:How to compare Series values in two different Dataframes and insert new value?如何比较两个不同数据框中的系列值并插入新值?
【发布时间】:2020-11-09 03:07:36
【问题描述】:

我想使用 GeoPandas 来可视化一些选举数据。我有两个 DataFrame - 第一个 DataFrame 包含几何数据和选区标签,第二个 DataFrame 包含投票数据。我想将第二个 DataFrame 中的一些投票数据添加到第一个 DataFrame 中。

这是第一个 DataFrame 的结构:

Precinct_2020   geometry
345 Precinct 4-8    POLYGON ((-95.93331 41.22970, -95.93330 41.230...
346 Precinct 4-9    POLYGON ((-95.95904 41.23577, -95.95889 41.235...
347 Precinct 4-3    POLYGON ((-95.94178 41.20966, -95.94178 41.211...
348 Precinct 2-17   POLYGON ((-95.95277 41.26891, -95.95255 41.270...
349 Precinct 8-83   POLYGON ((-96.04293 41.33597, -96.04294 41.337...

这是第二个DataFrame的结构:

Precinct_2020   diff
0   Precinct 1-2    67
1   Precinct 1-3    67
2   Precinct 1-4    27
3   Precinct 1-5    63
4   Precinct 1-7    43

我尝试通过使用两个嵌套 for 循环匹配区域标签来做到这一点,如下所示:

for entry in douglas_county_df:
  for item in voting_diff:
    if item['Precinct_2020'] in entry['Precinct_2020']:
      entry['diff'] = item['diff']

本质上,我想将第二个 DataFrame 中的投票差值“diff”添加到第一个 DataFrame 中的相应区域。我收到一个错误,字符串索引必须是整数。处理此问题的最佳方法是什么?

预期输出:

Precinct_2020   geometry
    345 Precinct 4-8    POLYGON ((-95.93331 41.22970, -95.93330 41.230... [diff for 4-8]
    346 Precinct 4-9    POLYGON ((-95.95904 41.23577, -95.95889 41.235... [diff for 4-9]
    347 Precinct 4-3    POLYGON ((-95.94178 41.20966, -95.94178 41.211... [diff for 4-3]
    348 Precinct 2-17   POLYGON ((-95.95277 41.26891, -95.95255 41.270... [diff for 2-17]
    349 Precinct 8-83   POLYGON ((-96.04293 41.33597, -96.04294 41.337... [diff for 8-83]

谢谢!

【问题讨论】:

  • 请分享您的预期输出。
  • 你有什么理由不做一个简单的merge?你可以entry = entry.merge(item, how='left', on='Precint_2020') ?
  • 会试一试。谢谢!
  • 如果您有两个要合并的数据框,请使用pandas.merge(df_left, df_right, how="left", on="Precinct_2020")。附加说明:df_leftdf_right 是您的数据框。如果您只需要来自df_right 数据帧的几列,请使用df_right[list_of_target_columns] 作为df_right。参考:pandas.DataFrame.merge - Docs

标签: python pandas dataframe


【解决方案1】:

解决方案

如果您有两个要合并的数据框,请使用(就像在 cmets 中提到的 David Erickson 一样):

COLUMN_TO_MERGE_ON = "Precinct_2020"
pandas.merge(df_left, df_right, how="left", on=COLUMN_TO_MERGE_ON)

注意:

  • 为了满足您的要求,我们使用left join。因此,how = left
  • df_leftdf_right 是您的数据框。如果您只需要 df_right 数据框中的几列,请使用 df_right[list_of_target_columns] 作为 df_right
  • 请参阅:Left join using merge in geopandas - 这个 stackexchange 问题向您展示了如何操作。 ?

参考资料:

我鼓励您探索以下参考资料。

【讨论】:

    猜你喜欢
    • 2022-11-16
    • 2018-04-01
    • 1970-01-01
    • 2019-02-13
    • 1970-01-01
    • 1970-01-01
    • 2022-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多