【问题标题】:How can I get the values with pandas idxmax function?如何使用 pandas idxmax 函数获取值?
【发布时间】:2021-02-18 10:29:46
【问题描述】:

当我们将 idxmax() 函数应用于 pandas DataFrame 时,它​​会返回表的索引和列。是否也有熊猫方法可以打印出值?

例如:

np.random.seed(seed=42)
df = pd.DataFrame(data=np.random.randint(0, 10, (10,10)),
           columns=["Test{}".format(x) for x in range(1, 10 + 1)],
            index=["Student{}".format(x) for x in range(1, 10 + 1)])

df.idxmax(axis =1)

它返回如下内容:

Student1      Test6
Student2      Test2
Student3      Test3
Student4      Test1
Student5      Test3
Student6     Test10
Student7      Test4
Student8      Test6
Student9      Test2
Student10     Test4

我也可以使用 pandas 为这些索引打印值吗?

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    DataFrame.aggidxmaxmax 一起使用:

    df = df.agg(['idxmax','max'],axis=1)
    print (df)
               idxmax max
    Student1    Test6   9
    Student2    Test2   7
    Student3    Test3   9
    Student4    Test1   8
    Student5    Test3   9
    Student6   Test10   9
    Student7    Test4   9
    Student8    Test6   9
    Student9    Test2   8
    Student10   Test4   9
    

    df1 = df.agg(['idxmax','max'],axis=1).astype({'max':int}).nlargest(5, 'max')
    print (df1)
    
              idxmax  max
    Student1   Test6    9
    Student3   Test3    9
    Student5   Test3    9
    Student6  Test10    9
    Student7   Test4    9
    

    【讨论】:

    • 跟进问题:我怎样才能让它只找到前几个值?说前 5 名
    • @JaySabir - 然后使用df.agg(['idxmax','max'],axis=1).nlargest(5, 'max')
    • 我怎样才能通过只找到前 5 个值而不是先计算所有 DataFrame 来使其更快?
    • @JaySabir - 嗯,它应该如何工作?因为您需要分别处理每一列。
    • @JaySabir - only finding top 5 values 之后 idxmax 之前的输出是什么?
    猜你喜欢
    • 2022-11-03
    • 1970-01-01
    • 2013-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-11-02
    相关资源
    最近更新 更多