【问题标题】:Get Index Minimum Value in Column When String - Pandas Dataframe获取字符串时列中的索引最小值 - Pandas Dataframe
【发布时间】:2020-06-04 00:39:13
【问题描述】:

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

给定以下 Pandas 数据框:

Platform | Action |    RPG    | Fighting
----------------------------------------
PC       |   4    |      6    |     9
Playstat |   6    |      7    |     5
Xbox     |   9    |      4    |     6
Wii      |   8    |      8    |     7

我试图获取“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]

【问题讨论】:

  • ign_data['RPG'].idxmin() 有效吗?
  • 确实如此,先生 :)

标签: python pandas dataframe indexing series


【解决方案1】:

使用Series.idxmin

df.set_index('Platform')['RPG'].idxmin()
#'Xbox'

或者@Quang Hoang 在 cmets 上的建议

df.loc[df['RPG'].idxmin(), 'Platform']

如果Platform 已经是索引:

df['RPG'].idxmin()

编辑

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

df.set_index('Platform').idxmin(axis=1)['Playstat']
#'Fighting'

如果已经是索引:

df.loc['Playstat'].idxmin()

【讨论】:

  • df.loc[df['RPG'].idxmin(), 'Platform'] 也可以在没有set_index 的情况下工作。
  • 好吧,所以这肯定有效,但我在清理列和索引的名称时犯了一个错误。我正在寻找的实际上是一种获取特定索引值最低的列名的方法。所以对于“Playstat”,我应该得到“Fighting”。
  • 为了清楚起见,我应该接受这个答案并写一个全新的问题吗?
  • 你可以检查编辑部分,我认为你只需要axis = 1 如果这不能解决你的问题并且更复杂,你应该创建一个新问题:)
猜你喜欢
  • 2016-10-18
  • 2018-06-09
  • 2022-06-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-02
相关资源
最近更新 更多