使用python / pandas我使用了melt()函数来转换我的数据

Person  Score1  Score2  V1  V2
A   1   4   6   8
B   2   5   3   6
C   3   6   4   7


成表格

 Person variable  value  V1  V2
0      A   Score1      1   6  8
1      B   Score1      2   3  6
2      C   Score1      3   4  7
3      A   Score2      4   6  8
4      B   Score2      5   3  6
5      C   Score2      6   4  7


我现在想在其中添加另一列V


  如果变量= Score1,则V = V1;如果变量= Score2,则= V2


导致:

  Person variable  value  V
0      A   Score1      1  6
1      B   Score1      2  3
2      C   Score1      3  4
3      A   Score2      4  8
4      B   Score2      5  6
5      C   Score2      6  7


我尝试使用var_name命名变量属性,但是它似乎并没有真正定义它,因此很难使用它来计算V列的值,有什么想法吗?

最佳答案

使用np.where

import numpy as np

df['v'] = np.where(df['variable']== 'Score1', df['V1'], df['V2'])

# if you want to drop the columns
# df.drop(['V1','V2], axis=1, inplace=True)

10-06 06:28