我有两个 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/