2

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

Henry Ecker
  • 34,399
  • 18
  • 41
  • 57
Henry
  • 29
  • 1
  • 4
  • Does this answer your question? [How to get a value from a cell of a dataframe?](https://stackoverflow.com/questions/16729574/how-to-get-a-value-from-a-cell-of-a-dataframe) – Henry Ecker Jul 13 '21 at 11:52

4 Answers4

2

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 using 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

Keks
  • 37
  • 8
imxitiz
  • 3,920
  • 3
  • 9
  • 33
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])
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
QuagTeX
  • 112
  • 1
  • 12
1

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.

Sawradip Saha
  • 1,151
  • 11
  • 14