3

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.

matrix.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

1 Answer 1

3

Indexing starts from 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 0 as you can see above.

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:

df[3][3]
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for your reply, but I still can not access df[2][5], which should be 25
Have you read my answer? I've stated that the first subscript is the column, and the next is the row, so 25 would be df[5][2] not df[2][5]
Thanks. It is odd that the first subscript is column, which is against the custom of most other languages. Is there any particular reason for that?
I don't know I thought it might be some convention that numpy also uses but numpy uses row,column as the order, I suspect it follow the same sematic that if your df columns had names such as 'col1', 'col2' etc.. then doing df['col1'][2] would select col1 row 3, I just tested what would happen if you did df[2]['col1'] and this raises a KeyError so it looks like it was a conscious design decision by the pandas devs

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.