我试图将每个单元格中的值替换为1,如果该值等于行中其他列的最高值。
这是我目前尝试的。
df_ref['max'] = df_ref.max(axis=1)
df_ref['col1'] = df_ref.col1.apply(lambda x:1 if (x==df_ref['max']) else 0)
先谢谢你
你就快到了,你不需要最大列,只需要在你的lambda函数中应用它,然后使用 .any()
你还需要你的过程在一个循环内的列。
import pandas as pd
#data
d = {'col1': [0, 1, 0.170531, 0.170533, 0.170531],
'col2': [0, 0, 0.005285, 0.005285, 0.005285],
'col3': [0, 0, 0.047557, 0.047557, 0.047557],
'col4': [1, 0, 0.482381, 0.003104, 0.482381],
'col5': [0, 0, 0.003104, 0.482458, 0.003104],
'col6': [0, 0, 0.001109, 0.001108, 0.001109]}
#create dataframe
df = pd.DataFrame(data = d)
#list of columns
columns = df.columns.tolist()
#loop over columns
for col in columns:
#change to 1 if value equals to the max in that row
df[col] = df[col].apply(lambda x:1 if (x==df.max(axis=1)).any() else 0)
print(df)
col1 col2 col3 col4 col5 col6
0 0 0 0 1 0 0
1 1 0 0 0 0 0
2 0 0 0 1 0 0
3 0 0 0 0 1 0
4 0 0 0 1 0 0