簡體   English   中英

根據另一個 dataframe 中的相應值更改 pandas dataframe 中的值

[英]Alter value in pandas dataframe based on corresponding value in another dataframe

我有兩個 pandas 數據幀。

  1. 第一個(df1)有兩列:'Country'(字符串)和'Population'(int)。 每行包含一個不同的國家及其相應的人口(約 200 行)。
  2. 第二個(df2)也有兩列:'Country'(字符串)和'Value'(int)。 每個國家/地區以隨機順序出現可變次數,並具有相應的值(數千行)。

我想將 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM