python - 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 的玩家行
解决方案
您可以为此使用 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])
推荐阅读
- c# - 在 datetime 中输入 null(C# 和 WPF)
- c# - InvalidOperationException:无法跟踪实体类型“Vessels”>的实例,因为另一个实例
- google-sheets - Data Studio 中一个单元格中的多个 URL 显示为一个组合 URL
- javascript - 使用 Chart.js 制作木偶
- forms - Symfony5 forms - render radio input inside label
- github - Remix IDE中文件资源管理器中浏览器下的随机“github”文件夹
- r - 在 R 中的数据框中包含 OR 的 IF 语句
- asp.net - 具有认知身份验证的 ASP.NET Core 混合 Razor 页面/React SPA 应用程序
- ios - 区分 SpriteKit 中的光源
- java - 从我的 android 应用程序打开特定的 whatsapp 联系人