【问题标题】:Returning the actual index value of max & min values from a Pandas Dataframe column从 Pandas Dataframe 列返回最大值和最小值的实际索引值
【发布时间】:2018-05-22 09:29:21
【问题描述】:

如何打印/返回特定值的索引?

movies_per_year = pd.DataFrame(movies_per_year)
movies_per_year.columns = ["count"]
print(movies_per_year)

        count
year       
1891      1
1893      1
1894      2
1895      2
1896      2
1898      5

在这里,我的索引是年份。我想返回 count 为 1 的所有索引。此外,movies_per_year.max() 返回 5。因此,它应该返回 1898

【问题讨论】:

标签: python python-3.x pandas dataframe


【解决方案1】:

np.where() - 返回满足给定条件的元素的位置索引:

In [31]: np.where(df['count'] == 1)[0]
Out[31]: array([0, 1], dtype=int64)

In [35]: np.nonzero(df['count'] == 1)
Out[35]: (array([0, 1], dtype=int64),)

如果您需要真正的索引值(标签)而不是它们的位置:

In [40]: df.index[df['count'] == 1]
Out[40]: Int64Index([1891, 1893], dtype='int64', name='year')

查找最大元素的索引:

In [32]: df['count'].idxmax()
Out[32]: 1898

【讨论】:

  • 太棒了!我只有一个疑问,如何打印所有计数为 1 的年份。例如,它应该打印 1891 和 1893。
  • 试试这个打印所有计数为 1 df.index[df['count'] == 1].tolist() 的年份——忽略这个我看到答案已经被编辑包含它。
  • @HamzaHaider,是的,我们可以使用Index.tolist() 方法将索引转换为Vanilla Python 列表。谢谢!
猜你喜欢
  • 2018-06-09
  • 1970-01-01
  • 2021-07-09
  • 2010-10-15
  • 1970-01-01
  • 1970-01-01
  • 2017-12-17
  • 1970-01-01
  • 2018-01-13
相关资源
最近更新 更多