gpt4 book ai didi

pandas - Python pandas 根据在另一个数据框中的查找将列添加到数据框中

转载 作者:行者123 更新时间:2023-12-04 15:57:45 25 4
gpt4 key购买 nike

我有 1 个 DF,其中包含每支 NBA 球队比赛的第一天和最后一天。每场比赛前后,我都有另一个带团队 ELO 的 DF。我想在 DF1 中添加 2 列,其中包含团队的 ELO 以及指定的第一个和最后一个日期。对于第一列中的日期,我想要 ELO1,第二列中的日期我想要 ELO2。如果有某种方法可以将 2 个 ELO 之间的差异直接放入 1 列中,那就更好了,因为这就是我最终要计算的内容。

DF1:

         first      last
team

ATL 2017-10-18 2018-04-10

BOS 2017-10-17 2018-04-11

BRK 2017-10-18 2018-04-11

CHI 2017-10-19 2018-04-11
[...]

DF2:

          date      team       ELO_before        ELO_after
65782 2017-10-18 ATL 1648.000000 1650.308911

65783 2017-10-17 BOS 1761.000000 1753.884111

65784 2017-10-18 BRK 1427.000000 1439.104231

65785 2017-10-19 CHI 1458.000000 1464.397752

65786 2018-04-10 ATL 1406.000000 1411.729285
[...]

提前致谢!

编辑 - 我想要的结果数据框如下所示:

DF3:

       first        last      ELO_before    ELO_after
team

ATL 2017-10-18 2018-04-10 1648.000000 1411.729285

BOS 2017-10-17 2018-04-11 1761.000000 [Elo2 for last game]

BRK 2017-10-18 2018-04-11 1427.000000 [Elo2 for last game]

CHI 2017-10-19 2018-04-11 1458.000000 [Elo2 for last game]

最佳答案

您可以为此使用 pandas.DataFrame.merge:

import pandas as pd

# frames from the question
df1 = pd.DataFrame(data={
'team': ['ATL', 'BOS', 'BRK', 'CHI'],
'first': ['2017-10-18', '2017-10-17', '2017-10-18', '2017-10-19'],
'last': ['2018-04-10', '2018-04-11', '2018-04-11', '2018-04-11']
}).set_index('team')

df2 = pd.DataFrame(data={
'date': ['2017-10-18', '2017-10-17', '2017-10-18', '2017-10-19', '2018-04-10'],
'team': ['ATL', 'BOS', 'BRK', 'CHI', 'ATL'],
'ELO_before': [1648.0, 1761.0, 1427.0, 1458.0, 1406.0],
'ELO_after': [1650.308911, 1753.884111, 1439.104231, 1464.397752, 1411.729285]
})

# merge on first and last
df1.reset_index(inplace=True)
df3 = df1.merge(df2.drop('ELO_after', axis=1), how='left', left_on=['team', 'first'], right_on=['team', 'date']).drop(['date'], axis=1)
df3 = df3.merge(df2.drop('ELO_before', axis=1), how='left', left_on=['team', 'last'], right_on=['team', 'date']).drop(['date'], axis=1)

# calculate the differences
df3['ELO_difference'] = df3['ELO_after'] - df3['ELO_before']
df3.set_index('team', inplace=True)

关于pandas - Python pandas 根据在另一个数据框中的查找将列添加到数据框中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51220127/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com