获取数据框中最大值的(行,列)索引

Get (row,col) indices of max value in dataframe

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

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

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

我试过:

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

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

使用 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()

returns:

('Phoenix', 'Phoenix')

你也可以试试这个

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 方法似乎更优雅。但是,我想知道在您的情况下(数据大小),哪种方法会更快。你能通过对你的完整数据计时这些功能来检查一下吗?

row_city, column_city = (df.max(axis=1).idxmax(), df.max(axis=0).idxmax())