【问题标题】:Get (row,col) indices of max value in dataframe获取数据框中最大值的(行,列)索引
【发布时间】:2015-06-12 20:06:32
【问题描述】:

我有一个看起来像这样的数据框。

import pandas as pd
data = [[5, 7, 10], [7, 20, 4,], [8, 1, 6,]]
cities = ['Boston', 'Phoenix', 'New York']
df = pd.DataFrame(data, columns=cities, index=cities)

输出:

         Boston  Phoenix   New York
Boston      5       7         10
Phoenix     7       20         4
New York    8       1          6

并且我希望能够找到具有最大价值的城市对。在这种情况下,我想返回 Phoenix,Phoenix。

我试过了:

cityMax = df.values.max()
cityPairs = df.idxmax()

第一个只给我最大值(20),第二个给我每个城市的最大值对,而不仅仅是整体最大值。有没有办法返回数据框中指定值的索引和列标题?

【问题讨论】:

标签: python numpy indexing max dataframe


【解决方案1】:

使用 unstack() 并使用 idxmax() 将顶部的 MultiIndex 提取为元组

import pandas as pd
data = [[5, 7, 10], [7, 20, 4,], [8, 1, 6,]]
cities = ['Boston', 'Phoenix', 'New York']
df = pd.DataFrame(data, columns=cities, index=cities)

print df.unstack().idxmax()

返回:

('Phoenix', 'Phoenix')

【讨论】:

    【解决方案2】:

    你也可以试试

    In [15]: df_mat = df.as_matrix()
    
    In [16]: cols, idxs = np.where(df_mat == np.amax(df_mat))
    
    In [17]: ([df.columns[col] for col in cols], [df.index[idx] for idx in idxs])
    Out[17]: (['Phoenix'], ['Phoenix'])
    

    @piemont 方法看起来更优雅。但是,我想知道在您的情况下(数据大小),哪种方法会更快。你能通过对你的完整数据计时这些函数来检查吗?

    【讨论】:

      【解决方案3】:
      row_city, column_city = (df.max(axis=1).idxmax(), df.max(axis=0).idxmax())
      

      【讨论】:

        猜你喜欢
        • 2022-06-13
        • 1970-01-01
        • 2018-08-04
        • 2022-07-25
        • 1970-01-01
        • 2021-08-25
        • 2018-06-09
        • 2013-02-03
        • 2016-07-09
        相关资源
        最近更新 更多