【问题标题】:Replace values in each cell based on other rows using lambda and apply i python使用 lambda 根据其他行替换每个单元格中的值并应用 i python
【发布时间】:2020-05-17 17:04:26
【问题描述】:

如果每个单元格中的值等于该行中其他列中的最大值,我会尝试将每个单元格中的值替换为 1。

This is the data i have

This is where i want to get to

这是我迄今为止尝试过的:

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)

提前致谢

【问题讨论】:

  • df_ref 是什么类型的对象?
  • 它是一个数据框

标签: python lambda data-science apply


【解决方案1】:

你快到了,你不需要 max 列,只需在你的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-22
    • 2021-04-22
    • 2019-05-16
    相关资源
    最近更新 更多