获取字符串时列中的索引最小值 - Pandas Dataframe

PYB*_*PYB 3 python indexing series dataframe pandas

我对此进行了一些研究,但是当索引为“字符串”类型时找不到简洁的方法。

给定以下 Pandas 数据框:

Platform | Action |    RPG    | Fighting
----------------------------------------
PC       |   4    |      6    |     9
Playstat |   6    |      7    |     5
Xbox     |   9    |      4    |     6
Wii      |   8    |      8    |     7
Run Code Online (Sandbox Code Playgroud)

我试图获取“RPG”列中最小值的索引(平台),这将返回“Xbox”。我设法让它工作,但效率不高,正在寻找更好/更快/更简洁的方法。这是我得到的:

# Return the minimum value of a series of all columns values for RPG
series1 = min(ign_data.loc['RPG'])

# Find the lowest value in the series
minim = min(ign_data.loc['RPG'])

# Get the index of that value using boolean indexing
result = series1[series1 == minim].index

# Format that index to a list, and return the first (and only) element
str_result = result.format()[0]
Run Code Online (Sandbox Code Playgroud)

ans*_*sev 7

使用Series.idxmin

df.set_index('Platform')['RPG'].idxmin()
#'Xbox'
Run Code Online (Sandbox Code Playgroud)

或者@Quang Hoang 对评论的建议

df.loc[df['RPG'].idxmin(), 'Platform']
Run Code Online (Sandbox Code Playgroud)

如果Platform已经是索引:

df['RPG'].idxmin()
Run Code Online (Sandbox Code Playgroud)

编辑

df.set_index('Platform').loc['Playstat'].idxmin()
#'Fighting'

df.set_index('Platform').idxmin(axis=1)['Playstat']
#'Fighting'
Run Code Online (Sandbox Code Playgroud)

如果已经是索引:

df.loc['Playstat'].idxmin()
Run Code Online (Sandbox Code Playgroud)

  • `df.loc[df['RPG'].idxmin(), 'Platform']` 也可以在没有 `set_index` 的情况下工作。 (2认同)