如何在Pandas中根据条件在其他列的基础上转移一列?

时间:2019-11-15 11:17:36

标签: python pandas dataframe

我有一个包含4列的数据框,我想创建一个(或多个)列,并向下移动一个(或多个)列,并以其他条件为条件,以使该列指示主队的先前得分(但是不必关心团队以前的状态(主队,客队),如下所示:

    HomeTeam    AwayTeam    Score_Home  Score_Away Score_Home_1
0   0           1           1.0         1.0        Nan
1   1           2           1.0         1.0        1.0
2   2           1           1.0         0.0        1.0      
3   0           2           3.0         0.0        1.0
4   2           0           0.0         0.0        1.0  
5   1           0           2.0         2.0        0.0
...

因此,我尝试了以下操作,但依我的意愿无法正常工作。

df[['score_{}'.format(i) for i in range(1, k+1)]] = pd.DataFrame({ 'score_{}'.format(i): np.zeros(df.shape[0]) for i in range(1, k+1)})
for idx in list(df.HomeTeam.unique()):
    x = df_copy.query("HomeTeam == @idx | AwayTeam == @idx")
    x = x[['HomeTeam', 'AwayTeam', 'Score_Home', 'Score_Away']]
    for i in range(1, k+1):
        df.loc[x.index, 'score_{}'.format(i)] = x.apply(lambda y: y.Score_Home if y.HomeTeam == idx else y.Score_Away, axis=1).shift(i)

那我想我错过了一件重要的事情。我不知道是否存在更好的方法。

0 个答案:

没有答案