根据其他数据框更改数据框的值

huangapple go评论86阅读模式
英文:

Change dataframe values based on other dataframes

问题

假设我们有名为“df1”的数据框,其列名为城市:

  1. 纽约 洛杉矶 罗马 伦敦 米兰
  2. 日期
  3. 2023-01-01 1 81 26 55 95
  4. 2023-01-02 92 42 96 98 7
  5. 2023-01-03 14 4 60 88 73

在另一个名为“df2”的数据框中,我有城市及其所属国家:

  1. 城市 国家
  2. 0 纽约 美国
  3. 1 洛杉矶 美国
  4. 2 伦敦 英国
  5. 3 罗马 意大利
  6. 4 米兰 意大利

在第三个名为“df3”的数据框中,我有每个国家和每个日期的一些值:

  1. 美国 英国 意大利
  2. 日期
  3. 2023-01-01 70 41 32
  4. 2023-01-02 98 46 45
  5. 2023-01-03 83 50 17

我的输出数据框与第一个数据框具有相同的结构。这是预期输出:

  1. 纽约 洛杉矶 罗马 伦敦 米兰
  2. 日期
  3. 2023-01-01 -69 11 -6 14 63
  4. 2023-01-02 -6 -56 51 52 -38
  5. 2023-01-03 -69 -79 43 38 56

例如,2023-01-02的“罗马”的值为51,这是df1中相同单元格的值(96)与“罗马”所在国家(意大利)在2023-01-02的值(45)之间的差异。

英文:

Let's say we have the following "df1" dataframe with cities as column names:

  1. NY LA Rome London Milan
  2. date
  3. 2023-01-01 1 81 26 55 95
  4. 2023-01-02 92 42 96 98 7
  5. 2023-01-03 14 4 60 88 73

In another "df2" dataframe I have cities and their countries:

  1. City Country
  2. 0 NY US
  3. 1 LA US
  4. 2 London UK
  5. 3 Rome Italy
  6. 4 Milan Italy

In a third "df3" dataframe I have some values for each country and each date:

  1. US UK Italy
  2. date
  3. 2023-01-01 70 41 32
  4. 2023-01-02 98 46 45
  5. 2023-01-03 83 50 17

My output dataframe has the same strutcture as the first dataframe. This is the expected output:

  1. NY LA Rome London Milan
  2. date
  3. 2023-01-01 -69 11 -6 14 63
  4. 2023-01-02 -6 -56 51 52 -38
  5. 2023-01-03 -69 -79 43 38 56

For example, the 51 value for "Rome" on 2023-01-02 is the difference between the value of the same cell from df1 (96) and the value of the country where Rome is located (Italy) on 2023-01-02 (45).

Any help? Thanks.

答案1

得分: 2

尝试堆叠df3,与df2合并以获取正确的城市数据,然后可以进行如下操作:

  1. df1.sub(df3.stack().reset_index(name='value')
  2. .merge(df2, left_on='level_1', right_on='Country')
  3. .pivot(index='date', columns='City', values='value')
  4. )

输出:

  1. 洛杉矶 伦敦 米兰 纽约 罗马
  2. 日期
  3. 2023-01-01 11 14 63 -69 -6
  4. 2023-01-02 -56 52 -38 -6 51
  5. 2023-01-03 -79 38 56 -69 43
英文:

Try stack df3, merge it with df2 to get the correct data for the cities, then you can sub:

  1. df1.sub(df3.stack().reset_index(name='value')
  2. .merge(df2, left_on='level_1', right_on='Country')
  3. .pivot(index='date', columns='City', values='value')
  4. )

Output:

  1. LA London Milan NY Rome
  2. date
  3. 2023-01-01 11 14 63 -69 -6
  4. 2023-01-02 -56 52 -38 -6 51
  5. 2023-01-03 -79 38 56 -69 43

huangapple
  • 本文由 发表于 2023年4月19日 22:39:11
  • 转载请务必保留本文链接:https://go.coder-hub.com/76055800.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定