python - 将 Pandas 数据框中的上层聚合的值连接到下层聚合

标签 python pandas

我有两个 Pandas 数据框。

第一个数据框(county)包含县级数据 -

COUNTY_FIPS    COUNTY_INCOME    COUNTY_PERCENT_UNINSURED
      51001            42260                        16.7
      51003            72265                         7.6

第二个数据框(tract)包含人口普查区域级数据 -

 TRACT_FIPS    TRACT_INCOME    TRACT_PERCENT_UNINSURED
51001090100           48861                       13.4
51001090200           42663                        9.4
51003090300           32532                       19.7
51003090100           55678                       12.1

我想将上层聚合(县级数据)的值连接到下层聚合(人口普查区级数据)。请注意,TRACT_FIPS 的前五个数字对应于这些人口普查区所在的县(请参阅 COUNTY_FIPS)。我的最终数据框将如下所示 -

 TRACT_FIPS    TRACT_INCOME    TRACT_PERCENT_UNINSURED    COUNTY_INCOME    COUNTY_PERCENT_UNINSURED
51001090100           48861                       13.4            42260                        16.7
51001090200           42663                        9.4            42260                        16.7 
51003090300           32532                       19.7            72265                         7.6
51003090100           55678                       12.1            72265                         7.6

这是我到目前为止编写的程序(使用一些伪代码) -

county_income_values = [] # empty list of county income values
county_percent_uninsured_values # empty list of county percent uninsured values

for tract_fips in tract['tract_fips']: # iterate through all the tract_fips in the tract_fips column
    for county_fips in county['county_fips']: # iterate through all the county_fips in the county_fips column
        if tract_fips[0:5] == county_fips: # if the first 5 digits of the tract_id match the county_id
            # TO DO: Find the index of where the if statement evaluates to true, and append the 
                     county income value at that index to county_income_values_list
            # TO DO: Find the index of where the if statement evaluates to true, and append the 
                     county percent uninsured value at that index to county_percent_uninsured_values 

如果有更有效的方法来解决这个问题,那么请随意忽略我上面的代码。

提前非常感谢!

最佳答案

您可以使用函数merge 。首先,您需要从第二个数据帧的 'TRACT_FIPS' 列中提取前五位数字。然后,您可以将'COUNTY_FIPS' 列转换为字符串并使用两列进行合并:

left = df2['TRACT_FIPS'].astype('str').str[:5]
right = df1['COUNTY_FIPS'].astype('str')

df2.merge(df1, left_on=left, right_on=right)

关于python - 将 Pandas 数据框中的上层聚合的值连接到下层聚合,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59967038/

相关文章:

python - 如何创建具有相同和不同长度的其他 numpy 数组的 numpy _object_ 数组?

python - 使 sklearn 中的网格搜索功能忽略空模型

python - fetchall() 对于 DELETE 查询抛出 "Previous SQL was not a query."

python - 如何在 Pandas 中做前向滚动总和?

pandas - '\u200d1500'是什么?

python - 将纪元时间转换为 Pandas 数据框中的格式化日期字符串

python - 有没有一种巧妙的方法来使用 pandas (或其他 python 工具)检查数组中所有值的区间是否包含在内?

python - 将一列字符串转换为 pandas 中的列表

python - 在 GPU 上提前

python - 提高 Python 中超大字典的性能