参考熔化变量列来计算数据框中的另一列

Reference melt variable column to calculate another column in datafrane

使用 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,其中

V = V1 if variable = Score1, else = V2 if variable = Score2

导致:

  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)

使用wide_to_long:

df = (pd.wide_to_long(df.reset_index(),stubnames=['Score','V'], i=['index'], j='variable')
       .reset_index(level=0, drop=True)
       .reset_index()
       .assign(variable= lambda x: 'Score' + x['variable'].astype(str))
       )
print (df)
  variable Person  Score  V
0   Score1      A      1  6
1   Score1      B      2  3
2   Score1      C      3  4
3   Score2      A      4  8
4   Score2      B      5  6
5   Score2      C      6  7