Calling an element of a dataframe

Viewed 1692

This is my first post here or in any programming forum.

I have a data frame made this way:

d = {'col1': [1, 2], 'col2': [3, 4]}
df = pd.DataFrame(data=d)

This results in a dataframe that has two rows and two columns (maybe three, if you count the index column?). I want to call what is in the first row and first column, for example. Or, maybe I want to call the first entire row, the one with index 0.

How do I do this? Apparently I cannot use either

df(1,1)
df[1,1]
df(1,:)

...and so on.

I dont understand if this documentation(https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.html) holds the solution or not, or if it says that it cannot be done. If it cannot be done, where does it say in the documentation?

I am really new to this, please have patience :)

/H

4 Answers

You can bacially select column using .iloc.

In your case, you can do this:

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4]}

df=pd.DataFrame(d)

print(df.iloc[0][0])
#.iloc[0] for first column and another .iloc[0][0] for first row from first column

Output is : 1

Or using name of the column you can do this:

import pandas as pd

d = {'col1': [1, 2], 'col2': [3, 4]}

df=pd.DataFrame(d)

print(df["col1][0])
#By doing df["col1] you can select that specific column link here 'col1' and df["col1][0], [0] for first row from that column.

Output is : 1

You can also call your desired values with your given column name

In [4]: s = df['col1']
Out[4]: s
0    1
1    2
In [5]: s[0]
Out[5]: 1

You can use iloc.

For knowing what is in the first column and first row:

print(df.iloc[0][0])

For calling the first row:

print(df.iloc[0])

You can access an element, or entire row or column with df.loc and also with df.iloc

Check the documentation links, and especially the examples.

Related