代码之家  ›  专栏  ›  技术社区  ›  Florent

如何遍历pandas行并根据行中的排名修改每个单元格?

  •  1
  • Florent  · 技术社区  · 6 年前

    我想遍历数据帧的行,并根据其行中的单元格排名将单元格修改为真(假)。

    import pandas as pd
    inp = [{'c1':10, 'c2':100, 'c3':50}, {'c1':11,'c2':110, 'c3':500}, {'c1':12,'c2':120, 'c3':5}]
    df = pd.DataFrame(inp)
    print (df)
       c1   c2   c3
    0  10  100   50
    1  11  110  500
    2  12  120    5
    

    我可以按行迭代并对pandas系列进行排序:

    for index, row in df.iterrows():
        print(row.rank(ascending=True))
    
    c1    1.0
    c2    3.0
    c3    2.0
    Name: 0, dtype: float64
    c1    1.0
    c2    2.0
    c3    3.0
    Name: 1, dtype: float64
    c1    2.0
    c2    3.0
    c3    1.0
    Name: 2, dtype: float64
    

    但我不知道如何在排名高于(低于或等于)2时将单元格修改为真(假),所以最终结果是这样的:

    print (res)
          c1    c2      c3
    0  False  True   False
    1  False  False   True
    2  False  True   False
    

    我怎样才能做到?

    1 回复  |  直到 6 年前
        1
  •  1
  •   jezrael    6 年前

    我认为需要 rank 具有 DataFrame.gt 对于 > :

    df = df.rank(ascending=True).gt(2)
    print(df)
          c1     c2     c3
    0  False  False  False
    1  False  False   True
    2   True   True  False
    

    细节 :

    print(df.rank(ascending=True))
        c1   c2   c3
    0  1.0  1.0  2.0
    1  2.0  2.0  3.0
    2  3.0  3.0  1.0
    

    编辑:

    为了 等级 每行添加 axis=1 :

    print(df.rank(ascending=True, axis=1))
        c1   c2   c3
    0  1.0  3.0  2.0
    1  1.0  2.0  3.0
    2  2.0  3.0  1.0
    
    df1 = df.rank(ascending=True, axis=1).gt(2)
    print(df1)
          c1     c2     c3
    0  False   True  False
    1  False  False   True
    2  False   True  False