【问题标题】:Get row-index values of Pandas DataFrame as list? [duplicate]获取 Pandas DataFrame 的行索引值作为列表? [复制]
【发布时间】:2013-08-23 21:56:32
【问题描述】:

我在试图找到这个答案时可能使用了糟糕的搜索词。现在,在索引 DataFrame 之前,我以这种方式获取列中的值列表...

 list = list(df['column']) 

...那我就在专栏set_index。这似乎是一个浪费的步骤。在索引上尝试上述操作时,我得到一个关键错误。

如何获取索引中的值(单索引和多索引)并将它们放入列表或元组列表中?

【问题讨论】:

  • 为什么你想要他们作为一个列表??
  • 如果您只是让这些手动传递给df.set_index(),那是不必要的。直接做df.set_index['your_col_name', drop=False],已经。
  • 至于 why... 我个人需要在调试(Evaluate Expression in PyCharm)期间将数据帧的索引值作为列表获取或在步骤之间进行仔细检查时始终以交互方式编程(例如,在 Jupyter 笔记本中)。

标签: python list pandas indexing


【解决方案1】:

要获得index 值作为tuples 的list/listIndex/MultiIndex,请执行以下操作:

df.index.values.tolist()  # an ndarray method, you probably shouldn't depend on this

list(df.index.values)  # this will always work in pandas

【讨论】:

  • 我得到 TypeError: 'list' object is not callable for using list(df.index.values)
  • @Bode 你可能在范围内还有另一个变量list
  • df.index.tolist() 就足够了。
【解决方案2】:

如果您只是让这些手动传递到df.set_index(),那是不必要的。 直接做df.set_index['your_col_name', drop=False],已经。

在 pandas 中很少需要将索引作为 Python 列表获取(除非你正在做一些非常时髦的事情,或者将它们传递回 NumPy),所以如果你经常这样做,这是一个代码味道,你做错了什么。

【讨论】:

    猜你喜欢
    • 2018-06-09
    • 2021-11-11
    • 1970-01-01
    • 2019-01-11
    • 1970-01-01
    • 2019-05-24
    • 1970-01-01
    • 2020-06-04
    • 2016-10-18
    相关资源
    最近更新 更多