如何创建基于某些特定列不是的新列?

时间:2019-11-20 09:53:42

标签: python pandas

我有以下示例:

away_team_id home_team_id team_id
1            4            1
3            7            3
6            25           25 
12           64           12

我想创建一个新的对手,即_team_id而不是team_id,它是这样的:

away_team_id home_team_id team_id opponent
1            4            1       4 
3            7            7       3
6            25           25      6
12           64           12      64

这是我尝试过的。

df['opponent'] = [df['away_team_id'] if df['team_id'] == df['home_team_id'] else df['home_team_id'] for team_id in df['team_id]]

我要去哪里错了?谢谢。

1 个答案:

答案 0 :(得分:0)

您可以使用一个numpy.where()来解决此问题:

import pandas as pd
import numpy as np

df = pd.DataFrame({
    'away_team_id': [1, 3, 6],
    'home_team_id': [4, 7, 25],
    'team_id': [1, 4, 25],
})

df['opponent'] = np.where(
    df['away_team_id'] == df['team_id'],  # condition
    df['home_team_id'],                   # when condition is True
    df['away_team_id']                    # when condition is False
)
df
#    away_team_id  home_team_id  team_id  opponent
# 0  1             4             1        4
# 1  3             7             4        3
# 2  6             25            25       6