【问题标题】:How to return the index value of an element in a pandas dataframe如何返回熊猫数据框中元素的索引值
【发布时间】:2018-07-02 10:29:43
【问题描述】:

我有一个特定股权的公司行为数据框。它看起来像这样:

0             Declared Date       Ex-Date    Record Date
BAR_DATE                 
2018-01-17       2017-02-21    2017-08-09     2017-08-11
2018-01-16       2017-02-21    2017-05-10     2017-06-05

除了它有数百行,但这并不重要。我从其中一列创建了索引“BAR_DATE”,其中 0 来自 BAR_DATE 上方。

我想要做的是能够引用数据框的特定元素并返回索引值或 BAR_DATE,我认为它会是这样的:

index_value = cacs.iloc[5, :].index.get_values()

除了 index_value 成为列名,而不是索引。现在,这可能源于对 pandas 数据帧中的索引的理解不足,因此对于其他人来说,这可能真的很容易解决,也可能不容易解决。

我查看了许多其他问题,包括 this one,但它也返回列值。

【问题讨论】:

  • 很多解释......但你到底在寻找什么?您的预期输出是什么?
  • 你能给出一个最小的工作示例,说明它在哪里给你列名而不是索引?我无法重现这种行为......
  • 我想要数据框任何特定元素的索引值。
  • 只需删除您对get_values() 的调用,因为调用.index 返回切片的索引。
  • 试试:cacs.iloc[5, :].index.item()?

标签: python


【解决方案1】:

你的代码真的很接近,但你比你需要的更进一步。

# creates a slice of the dataframe where the row is at iloc 5 (row number 5) and where the slice includes all columns
slice_of_df = cacs.iloc[5, :]

# returns the index of the slice
# this will be an Index() object
index_of_slice = slice_of_df.index

从这里我们可以使用Index 对象的文档:https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Index.html

# turns the index into a list of values in the index
index_list = index_of_slice.to_list()

# gets the first index value
first_value = index_list[0]

关于Index,要记住的最重要的一点是它是一个自己的对象,因此如果我们想要索引以外的东西,我们需要将它更改为我们期望使用的类型。这就是文档可以提供巨大帮助的地方。

编辑: 事实证明,在这种情况下 iloc 返回一个 Series 对象,这就是解决方案返回错误值的原因。知道了这一点,新的解决方案将是:

# creates a Series object from row 5 (technically the 6th row)
row_as_series = cacs.iloc[5, :]

# the name of a series relates to it's index
index_of_series = row_as_series.name

这将是单行索引的方法。您可以将前一种方法用于多行索引,其中返回值为DataFrame 而不是Series

不幸的是,我不知道如何将 Series 强制转换为 DataFrame 以进行显式转换之外的单行切片:

row_as_df = DataFrame(cacs.iloc[5, :])

虽然这会起作用,并且第一种方法会很高兴地采用它并返回索引,但 Pandas 没有为单行切片返回 DataFrame 可能是有原因的,所以我很犹豫是否将其作为解决方案。

【讨论】:

  • 好的,所以这非常接近,但它仍然返回我接近时得到的东西。使用 index_of_slice = slice.index 返回列标题,而不是 BAR_DATE。
  • 就好像通过取整行的一部分,解释器认为我想要列索引;它认为我想要跨行进行测量,而不是整行的共同值。
  • 编辑正是我想要的。我一看到 .name 就知道了,我也对其进行了测试,但它确实有效。非常感谢。
  • 完全没问题:)。很高兴我能帮上忙。
猜你喜欢
  • 2017-09-17
  • 2017-06-08
  • 2023-04-07
  • 2016-07-19
  • 2021-03-17
  • 2022-07-10
  • 2019-05-21
  • 2020-02-19
  • 1970-01-01
相关资源
最近更新 更多