【问题标题】:ValueError: Wrong number of items passed 5, placement implies 1, error while finding the second max value in a rowValueError:错误的项目数通过 5,位置意味着 1,在连续找到第二个最大值时出错
【发布时间】:2022-01-13 17:40:36
【问题描述】:

获取数据框中每一行的第二个最大值,但得到值错误

column = [col for col in dataframe.columns if '%' in col]

dataframe["Max_2nd"] = dataframe[column].apply(lambda row: row.nlargest(2).values[-1],axis=1)

我该如何解决这个问题

【问题讨论】:

    标签: python pandas group-by max


    【解决方案1】:

    所以,给定以下玩具数据框:

    import pandas as pd
    
    df = pd.DataFrame(
        (
            {
                "col1": [1, 2, 3, 4, 5, 6, 7, 8],
                "col2": [3, 0, 1, 3, 0, 1, 8, 5],
                "col3": [7, 9, 2, 6, 7, 8, 0, 1],
                "col4": [0, 4, 5, 0, 4, 3, 4, 0],
            }
        )
    )
    

    您可以像这样在每一行中找到第二个最大值:

    df["Max_2nd"] = df.apply(lambda x: sorted(x, reverse=True)[1], axis=1)
    
    print(df)
    # Outputs
       col1  col2  col3  col4  Max_2nd
    0     1     3     7     0        3
    1     2     0     9     4        4
    2     3     1     2     5        3
    3     4     3     6     0        4
    4     5     0     7     4        5
    5     6     1     8     3        6
    6     7     8     0     4        7
    7     8     5     1     0        5
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-03
      • 2022-07-19
      • 2019-09-23
      • 2019-05-17
      • 2021-11-26
      • 2020-10-30
      • 2020-09-17
      • 2019-03-19
      相关资源
      最近更新 更多