python - 如何根据 dfB 中的列/行值,使用另一个数据帧 (dfB) 中的值填充 pandas 数据帧 (dfA) 列 "A"?

标签 python pandas dataframe

我有一个 df (dfA),其中包含 6 个国家的出生预期生命周期和每年 GDP。具有以下 structure :

country  year  expectancy  gdp  difference
chile    2000    60       1bn     NA
chile    2001    63       1.5bn  0.5bn
chile    2002    65       2.5bn  0.5bn
chile    2003    68       3.5bn  1.0bn
  .
  .
  .
chile    2015    80      10bn     10bn

每行代表一个国家/地区每年的数据(GDP、预期等),涵盖 2000 年至 2015 年,涉及 6 个国家/地区。

我创建了一个新的数据框架来存储每个国家的重要整体变量,例如每个国家的 GDP 增量(2015 年的 GDP 减去 2000 年的 GDP)。新的 df (dfB) 看起来像 this :

country   startEndDelta (dummydata)
Chile        x
China        y
Germany      z
Mexico       a
USA          b
Zimbabwe     c

我想要做的是在我的 newdf 中添加一个新列,显示每个国家的 GDP 增幅最大的年份。

我已经能够计算年份,但我首先必须创建另一个仅包含一个国家/地区记录的数据框。 Here I do it the way I metioned before.

我希望这样做的方式类似于:

dfB['biggestDeltaYear'] = ?year with the biggest increase in GDP?

这一行代码填充 dfB 中我的新列“biggestDeltaYear”的每一行。

我有什么选择?

非常感谢

最佳答案

也许你可以尝试使用 pandas.DataFrame 的 groupby() 方法

dfA.groupby('country').apply(lambda x:x['year'].iloc[x['difference'].argmax()])

关于python - 如何根据 dfB 中的列/行值,使用另一个数据帧 (dfB) 中的值填充 pandas 数据帧 (dfA) 列 "A"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60425574/

相关文章:

python - Pandas 条形图 : Add marker to distinguish 0 and NaN

python - 根据单元格类型展开 pandas 列

python - 将列表转换为 DataFrame 时如何处理错误 "' NoneType' object has no attribute 'keys' "

python - Plotly-Dash:为每个选定的 df 列添加新的 y 轴

python - `console_scripts` 如何从 `package_data` 访问文件

python - 在Eclipse Pydev控制台和Idle中打印Unicode

python - 如何在numpy中设置固定的随机种子?

python替换为捕获组

python - 如何有效地计算 Pandas 数据框中的运行最大值?

python - 从合并列的代码中获取类别类型