我有1000 x 6数据框,其中A,B,C,D被人们以1-10的等级评分。
在SELECT列中,我有一个值,在所有情况下都与A / B / C / D中的任何一个值相同。
我想将“ SELECT”中的值更改为与其匹配的列的名称。例如,对于ID 1,SELECT = 1,D = 1,因此select的值应更改为D。
import pandas as pd
df = pd.read_excel("u.xlsx",sheet_name = "Sheet2",header = 0)
但是我迷路了。
Gwenersl解决方案比较不带列的所有列,ID
并用()进行SELECT
过滤,用来检查第一个值,如果不存在,则用以下值匹配设置值:difference
DataFrame.eq
==
True
idxmax
no match
numpy.where
cols = df.columns.difference(['ID','SELECT'])
mask = df[cols].eq(df['SELECT'], axis=0)
df['SELECT'] = np.where(mask.any(axis=1), mask.idxmax(axis=1), 'no match')
print (df)
ID A B C D SELECT
0 1 4 9 7 1 D
1 2 5 7 2 8 C
2 3 7 4 8 6 C
详细说明:
print (mask)
A B C D
0 False False False True
1 False False True False
2 False False True False
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句