获取Pandas DataFrame第一列

qlfbtfca  于 2023-04-04  发布在  其他
关注(0)|答案(2)|浏览(214)

假设简单 Dataframe :

import pandas as pd
a = pd.DataFrame([[0,1], [2,3]])

我可以很容易地切片这个 Dataframe ,第一列是a[[0]],第二列是a[[1]]
现在,让我们有更复杂的 Dataframe 。这是我的代码的一部分:

frame = pd.DataFrame(range(100), columns=["Variable"], index=["_".join(["loc", str(i)]) for i in range(1, 101)])
frame[1] = [i**3 for i in range(100)]

DataFrame frame也是一个pandas DataFrame。我可以通过frame[[1]]获得第二列。但是当我尝试frame[[0]]时,我得到一个错误:

Traceback (most recent call last):

  File "<ipython-input-55-0c56ffb47d0d>", line 1, in <module>
    frame[[0]]

  File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python-    3.5.2.amd64\lib\site-packages\pandas\core\frame.py", line 1991, in __getitem__
    return self._getitem_array(key)

  File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python-    3.5.2.amd64\lib\site-packages\pandas\core\frame.py", line 2035, in     _getitem_array
    indexer = self.ix._convert_to_indexer(key, axis=1)

  File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python-    3.5.2.amd64\lib\site-packages\pandas\core\indexing.py", line 1184, in     _convert_to_indexer
    indexer = labels._convert_list_indexer(objarr, kind=self.name)

  File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python-    3.5.2.amd64\lib\site-packages\pandas\indexes\base.py", line 1112, in     _convert_list_indexer
    return maybe_convert_indices(indexer, len(self))

  File "C:\Users\Robert\Desktop\Záloha\WinPython-64bit-3.5.2.2\python-    3.5.2.amd64\lib\site-packages\pandas\core\indexing.py", line 1856, in     maybe_convert_indices
    raise IndexError("indices are out-of-bounds")

IndexError: indices are out-of-bounds

我仍然可以使用frame.iloc[:,0],但问题是我不明白为什么我不能使用[[]]的简单切片?我使用winpython spyder 3。

vuktfyat

vuktfyat1#

使用您的代码:

import pandas as pd

var_vec = [i for i in range(100)]
num_of_sites = 100
row_names = ["_".join(["loc", str(i)]) for i in 
             range(1,num_of_sites + 1)]
frame = pd.DataFrame(var_vec, columns = ["Variable"], index = row_names)
spec_ab = [i**3 for i in range(100)]
frame[1] = spec_ab

如果你要求打印出“帧”,你会得到:

Variable    1
loc_1   0       0
loc_2   1       1
loc_3   2       8
loc_4   3       27
loc_5   4       64
loc_6   5       125
......

所以问题的原因很明显,没有名为'0'的列,在第一行指定了名为var_vec的列表,在第4行用该列表创建了一个dataframe,但是指定了索引值和列名(这通常是一个很好的做法)。与第一个示例一样,数字列名'0',' 1',..仅在不指定列名时才会发生,它不是列位置索引器。
如果要按列的位置访问列,可以:

df[df.columns[0]]

接下来发生的是,你得到了df的列列表,你选择了术语'0',并将其作为引用传递给df。
希望这能帮助你理解
编辑:
另一种(更好的)方法是:

df.iloc[:,0]

其中“:”代表所有行。(也按从0到行范围的数字索引)

wfveoks0

wfveoks02#

[]__getitem__()的 Package 器,它通过标签进行选择,正如@epattaro所解释的那样,在OP中创建的 Dataframe 中没有列标签0。要通过位置选择列(或行),规范的方法是通过iloc

df.iloc[:, 0]         # select first column as a Series
df.iloc[:, [0]]       # select first column as a single column DataFrame

df.iloc[0]            # select first row as a Series
df.iloc[[0]]          # select first row as a single row DataFrame

另一种方法是take()

df.take([0], axis=1)  # select first column
df.take([0])          # select first row

您可以验证对于任何dfdf.take([0], axis=1).equals(df.iloc[:, [0]])都返回True。

相关问题