根据索引在熊猫数据框中查找特定列的值[重复]

Posted

技术标签:

【中文标题】根据索引在熊猫数据框中查找特定列的值[重复]【英文标题】:Finding values in pandas dataframe for a particular column based on index [duplicate] 【发布时间】:2019-08-05 01:16:51 【问题描述】:

我正在使用 Python - 3.6 和 pandas - 0.24.1

我有一个熊猫数据框df1

    col1    col2
0  8388611  3.9386
1  8388612  1.9386

我需要在特定索引上找到col1 的值

 print(df1['col1'][1])

错误:

Traceback (most recent call last):
  File "/home/runner/.site-packages/pandas/core/indexes/base.py", line 2656, inget_loc
    return self._engine.get_loc(key)
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "main.py", line 24, in <module>
    print(df1['col1'][1])
  File "/home/runner/.site-packages/pandas/core/frame.py", line 2927, in __getitem__
    indexer = self.columns.get_loc(key)
  File "/home/runner/.site-packages/pandas/core/indexes/multi.py", line 2397, in get_loc
    loc = self._get_level_indexer(key, level=0)
  File "/home/runner/.site-packages/pandas/core/indexes/multi.py", line 2652, in _get_level_indexer
    code = level_index.get_loc(key)
  File "/home/runner/.site-packages/pandas/core/indexes/base.py", line 2658, inget_loc
    return self._engine.get_loc(self._maybe_cast_indexer(key))
  File "pandas/_libs/index.pyx", line 108, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index.pyx", line 132, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/hashtable_class_helper.pxi", line 1601, in pandas._libs.hashtable.PyObjectHashTable.get_item
  File "pandas/_libs/hashtable_class_helper.pxi", line 1608, in pandas._libs.hashtable.PyObjectHashTable.get_item
KeyError: 1

在 pandas 中迭代特定列的所有元素的理想方法是什么?

【问题讨论】:

使用print(df1.loc[1, 'col1']),是骗子 【参考方案1】:

你可以使用 iloc

df["column"].iloc[index]

【讨论】:

以上是关于根据索引在熊猫数据框中查找特定列的值[重复]的主要内容,如果未能解决你的问题,请参考以下文章

如何在熊猫数据框中查找列的 ngram 频率?

根据火花数据框中另一列的值查找列的最大值?

如何在熊猫数据框中查找缺失的索引值?

熊猫根据索引标签选择特定列中的值[重复]

在熊猫数据框中查找重复行

遍历熊猫数据框中的列