首页 > 解决方案 > python数据框根据其他列值合并列

问题描述

我想要做的是根据另一列中的值合并列最好用一个简单的例子来说明:我有一个包含 5 列的数据框:

| player_num    | team_1.x  | team_1.y  | team_2.x  | team_2.y  |
|------------   |---------- |---------- |---------- |---------- |
| 1             | x_1       | y_1       | x_2       | y_2       |
| 4             | x_3       | y_3       | x_4       | y_4       |
| 8             | x_5       | y_5       | x_6       | y_6       |

我想得到下表:

| x     | y     |
|-----  |-----  |
| x_1   | y_1   |
| x_3   | y_3   |
| x_6   | y_6   |

其中列填充了来自 team_1.x 和 team_1.y 的值,用于数字小于 5 的玩家行,以及来自 team_2.x 和 team_2.y 的值用于数字大于 5 的玩家行

标签: pythonpandasdataframe

解决方案


您可以为此使用 Numpy 的 np.where :

import numpy as np
...
df['x'] = np.where(df['player_num'] < 5, df['team_1.x'], df['team_2.x'])
df['y'] = np.where(df['player_num'] < 5, df['team_1.y'], df['team_2.y'])

编辑:

# Extract column names and remove prefix to get a list of x,y,z, etc.
cols = [col.split('.')[1] for col in list(df) if 'team_' in col]

# Loop over and create new column for each prefix (x, y, z, etc)
for col in cols:
    col1 = 'team_1.' + col
    col2 = 'team_2.' + col
    df[col] = np.where(df['player_num']<5, df[col1], df[col2])

推荐阅读