Accessing an element in pandas dataframes

Asked

Viewed 2,054 times

0

I would like to access the first element of the pandas dataframe.

import pandas as pd

data = [['2019', '0000', 'protocolo'], ['2020', '1111', 'pedido']]
df = pd.DataFrame(data)

Trying:

df = df.sort_values(by=['2019', '0000'])

Error:

raise Keyerror(key)

Keyerror: '2019'

1 answer

2


The dataframe created by your code has the following form:

      0     1          2
0  2019  0000  protocolo
1  2020  1111     pedido

Making df = df.sort_values(by=['2019', '0000']), you are trying to access the name columns 2019 and 0000, hence the error

Keyerror: '2019'

But 2019 is a value, not the name of a column.

One way to directly access the values is

>>> df[0][0]
2019
>>> df[0].values
array(['2019', '2020'], dtype=object)
>>> df.iloc[0].values
array(['2019', '0000', 'protocolo'], dtype=object)

Browser other questions tagged

You are not signed in. Login or sign up in order to post.