Python/Pandas:如何在一列中选择值等于另一列中不同行的行?

2024-10-02 00:20:19 发布

您现在位置:Python中文网/ 问答频道 /正文

以下是我的数据示例:

In[177]:df_data[['Date', 'TeamName', 'Opponent', 'ScoreOff']].head()
Out[177]: 
                     Date              TeamName              Opponent   ScoreOff
4128  2005-09-08 00:00:00  New England Patriots       Oakland Raiders   30
4129  2005-09-08 00:00:00       Oakland Raiders  New England Patriots   20
4130  2005-09-11 00:00:00     Arizona Cardinals       New York Giants   19
4131  2005-09-11 00:00:00      Baltimore Ravens    Indianapolis Colts   7
4132  2005-09-11 00:00:00         Buffalo Bills        Houston Texans   22

对于每一行,我需要设置一个新的列['OpponentScoreOff']等于该队对手当天的得分。在

我基本上是这样做的,但是速度很慢,而且我觉得有一种更像Python的/矢量化的方法。在

^{pr2}$

它起作用了,但很慢。有更好的办法吗?在


Tags: 数据in示例dfnewdatadatehead
1条回答
网友
1楼 · 发布于 2024-10-02 00:20:19

您可以使用sort来利用TeamName和Opponent在任何给定日期之间的双向映射。考虑以下因素:

import pandas as pd
import numpy as np

df_data = df_data.sort(['Date', 'TeamName'])
opp_score = np.array(df_data.sort(['Date', 'Opponent'])['ScoreOff'])
df_data['OpponentScoreOff'] = opp_score

数组调用是删除数据帧索引所必需的。这样,一旦数组被放回df_data,它就不会被重设。在

相关问题 更多 >

    热门问题