【问题标题】:Create new columns which show values based on ranking of other columns python创建基于其他列python的排名显示值的新列
【发布时间】:2019-04-03 07:54:33
【问题描述】:

我有一个数据框,其中包含一些日期作为行和列中的值。要知道 df 如下所示:

print(df1)

            c1  c2  c3  c4
12/12/2016  38  10   1   8
12/11/2016  44  12  17  46
12/10/2016  13   6   2   7
12/09/2016   9  16  13  26

我想创建一个规则,以便它对 df1 中的每一行进行排名,并创建另一个数据框来存储一些常量值。例如,对于每行中的 2 个最高值,它分配值 k = 5,对于最低 2 个值,它显示值 y = -9

我想获得的是以下df:

            c1  c2  c3  c4
12/12/2016  5    5  -9  -9
12/11/2016  5  -9   -9   5
12/10/2016  5  -9   -9   5
12/09/2016  -9  5   -9   5

我曾考虑在 df1 上使用 np.partition,但我对如何创建新数据框感到困惑。任何提示都非常感谢!

谢谢!

【问题讨论】:

    标签: python pandas dataframe partitioning partition


    【解决方案1】:

    ranknumpy.whereDataFrame 构造函数一起使用:

    arr = np.where(df.rank(axis=1, method='dense') > 2, 5, -9)
    
    df = pd.DataFrame(arr, index=df.index, columns=df.columns)
    print (df)
                c1  c2  c3  c4
    12/12/2016   5   5  -9  -9
    12/11/2016   5  -9  -9   5
    12/10/2016   5  -9  -9   5
    12/09/2016  -9   5  -9   5
    

    【讨论】:

      【解决方案2】:

      这是一个 NumPy 解决方案:

      df.iloc[:] = np.where(df.values.argsort(1).argsort(1) > 1, 5, -9)
      
      print(df)
      
                  c1  c2  c3  c4
      12/12/2016   5   5  -9  -9
      12/11/2016   5  -9  -9   5
      12/10/2016   5  -9  -9   5
      12/09/2016  -9   5  -9   5
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-12-30
        • 1970-01-01
        • 2019-09-18
        相关资源
        最近更新 更多