Pandas:按行号和列号访问数据框中的数据

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29335465/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:07:46  来源:igfitidea点击:

Pandas: access data from dataframe by row and column number

pythonpandasdataframe

提问by lserlohn

I have a simple program made me confused. I read a 3 * 10 data from a csv file, and I want to access a particular data by its row and column number. But it failed, I doun't know why.

我有一个简单的程序让我很困惑。我从 csv 文件中读取了 3 * 10 数据,并且我想通过其行号和列号访问特定数据。但它失败了,我不知道为什么。

matrix.txt:

矩阵.txt:

1,2,3,4,5,6,7,8,9,10
11,12,13,14,15,16,17,18,19,20
21,22,23,24,25,26,27,28,29,30

Program:

程序:

datainput = pd.read_csv('matrix.txt',sep=',', header = None)

inputinfo = datainput.shape ==> 3, 10

print datainput[3][3] => failed,but it should return 23, 

I can not access any data if the column number is equal or greater than 3

如果列号等于或大于 3,我将无法访问任何数据

回答by EdChum

Indexing starts from 0:

索引从 0 开始:

In [8]:

df
Out[8]:
    0   1   2   3   4   5   6   7   8   9
0   1   2   3   4   5   6   7   8   9  10
1  11  12  13  14  15  16  17  18  19  20
2  21  22  23  24  25  26  27  28  29  30

In [11]:

df[2][2]
Out[11]:
23

As you've not supplied a header one is auto generated and also for the index, the default behaviour is to generate indices starting from 0as you can see above.

由于您没有提供自动生成的标头,而且还为索引提供了标头,因此默认行为是从0上面看到的开始生成索引。

Also your last statement is not true:

另外你的最后一句话是不正确的:

In [13]:

df[3][2], df[5][2]
Out[13]:
(24, 26)

Here the first subscript value is the column label followed by the row label.

这里的第一个下标值是列标签,然后是行标签。

The following does raise a KeyError:

以下确实会引发 KeyError:

df[3][3]