根据另一个数据框中的相应值更改熊猫数据框中的值

时间:2020-07-21 10:03:04

标签: python pandas dataframe

我有两个熊猫数据框。

  1. 第一个(df1)有两列:“国家”(字符串)和“人口”(整数)。每行包含一个不同的国家及其相应的人口(约200行)。
  2. 第二个(df2)也有两列:“国家”(字符串)和“值”(整数)。每个国家/地区以随机顺序出现可变次数的次数,并具有相应的值(数千行)。

我想将df2 ['Value']中的每个值除以该行国家/地区的相应人口。

我的尝试:(假设有一个名为“国家/地区”的列表,其中包含这些数据框中的所有国家/地区

for country in countries:
  val = df2.loc[df2['Country'] == country]['Values'] # All values corresponding to country
  pop = df1.loc[df1['Country'] == country]['Population'] # Population corresponding to country
  df2.loc[df2['Country'] == country]['Values'] = val / pop

有更好的方法吗?也许不涉及for循环的解决方案?

谢谢

3 个答案:

答案 0 :(得分:1)

尝试以下操作:

# Assuming that there are the same countries in both df    
df3 = pd.merge(df2, df1, how = 'inner' on='Country')
df3["Values2"] = df3["Values"] / df3["Population"]

答案 1 :(得分:1)

另一种实现方式是在应用除法运算符之前将两个表连接起来。符合以下条件的东西:

df2 = df2.join(df1,on='Country',how='left')
df2['Values'] = df2['Values'] / df2['Population']

答案 2 :(得分:0)

您可以使用merge

df3 = df2.merge(df1, on='Country') # maybe you want to use how='left'
df3['Div'] = df3['Values'] / df3['Population']

您可以了解有关合并in the docs

的更多信息