python - 在 Pandas 中加入键不相等的地方

标签 python pandas dataframe

我有一个这样的数据框:

data = {'teamid': [1, 2, 3, 4], 'gameid': [1, 1, 2, 2], 'rebounds': [20, 35, 43, 15]}
game_df = pd.DataFrame(data=data)
print(game_df)

   teamid  gameid  rebounds
0       1       1        20
1       2       1        35
2       3       2        43
3       4       2        15

我想自己加入它来生成这样的数据框:

wanted_data = {'teamid': [1, 2, 3, 4], 'gameid': [1, 1, 2, 2], 'rebounds': [20, 35, 43, 15],
               'teamid_opponent': [2, 1, 4, 3], 'rebound_opponent': [35, 20, 15, 43]}
wanted_df = pd.DataFrame(data=wanted_data)
print(wanted_df)

   teamid  gameid  rebounds  teamid_opponent  rebound_opponent
0       1       1        20                2                35
1       2       1        35                1                20
2       3       2        43                4                15
3       4       2        15                3                43

在 SQL 中我会做这样的事情:

SELECT * from game_df df1 join game_df df2 on df1.gameid = df2.gameid and df1.teamid != df2.teamid

但我无法在 pandas 文档或此处找到任何在 pandas 本身中复制它的方法。我在这里查看并找到了这个 link但它与我正在尝试做的不太一样。我只找到了尝试在键相等的地方加入的例子。

最佳答案

这是使用merge的一种方式

Yourdf=game_df.merge(game_df,on='gameid',suffixes =['','_opponent']).query('teamid!=teamid_opponent')
Out[42]: 
   teamid  gameid  rebounds  teamid_opponent  rebounds_opponent
1       1       1        20                2                 35
2       2       1        35                1                 20
5       3       2        43                4                 15
6       4       2        15                3                 43

关于python - 在 Pandas 中加入键不相等的地方,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58119487/

相关文章:

python - Pandas 在 group by 之后连接一行,然后重新采样

python - Pandas 的速度 df.loc[x, 'column' ]

Pandas : 'pad' 与 'ffill' 相同吗?

python - 扁平化 pandas 数据框的最有效方法是什么?

python - 查询hdf5日期时间列

python - Pandas 对所有行进行排序

python - Future 的 exec_ 是如何工作的?

python - 我想使用 LADS DAAC 站点中提供的 Python 脚本从 HTTP 站点下载 MODIS 数据。但是在运行脚本时出现错误

python - 从列表中找到最多的 "consensus"字符串

python - 按条件替换 pandas 数据框列中的值