acces pandas rows values in python

You can access rows in pandas DataFrame using the .iloc method. The .iloc method is an indexer that allows you to select rows and columns by their integer positions.

For example, to access the first row of a DataFrame you would use the following code:

main.py
import pandas as pd

df = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']})

first_row = df.iloc[0]

print(first_row)
133 chars
8 lines

This code creates a new DataFrame using the pd.DataFrame method, and selects the first row of the DataFrame using the .iloc method. The resulting output should be:

main.py
Column1    1
Column2    A
Name: 0, dtype: object
49 chars
4 lines

Here, Column1 and Column2 are the names of the columns in the DataFrame, 1 and A are the values of the first row.

You can also select multiple rows with a single command:

main.py
import pandas as pd

df = pd.DataFrame({'Column1': [1, 2, 3], 'Column2': ['A', 'B', 'C']})

multiple_rows = df.iloc[0:2]

print(multiple_rows)
143 chars
8 lines

This code selects the rows from position 0 to position 1 (excluding position 2) and prints them out.

main.py
   Column1 Column2
0        1       A
1        2       B
57 chars
4 lines

related categories

gistlibby LogSnag