![](/img/trans.png)
[英]Sorting pandas value based on another dataframe values
[英]Alter value in pandas dataframe based on corresponding value in another dataframe
我有兩個 pandas 數據幀。
我想將 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 循環的解決方案?
謝謝
嘗試以下操作:
# 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"]
另一種實現是在應用除法運算符之前連接兩個表。 有點像:
df2 = df2.join(df1,on='Country',how='left')
df2['Values'] = df2['Values'] / df2['Population']
您可以為此使用merge
:
df3 = df2.merge(df1, on='Country') # maybe you want to use how='left'
df3['Div'] = df3['Values'] / df3['Population']
您可以在文檔中閱讀有關合並的更多信息
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.