In this post, we will go over the most common commands for Pandas rows.

I will use some dummy data for this post.

Let us import the Pandas first.

import pandas as pd

Let us prepare our dummy Dataframe.

df = pd.DataFrame([{'Name':'Alex','Age':24,'Height':6},{'Name':'John','Age':40,'Height':5.8},
                   {'Name':'Renee','Age':26,'Height':5.9}])
print(df)
	Name 	Age	Height
0	Alex	24	6.0
1	John	40	5.8
2	Renee	26	5.9

Select Rows in Pandas

We can select rows by index or index name.

1. Pandas access row by index name

df.loc[0]
Name      Alex
Age         24
Height       6
Name: 0, dtype: object

We can also give the index string names as shown below.

df.rename(index={0: 'zero',1:'one',2:'two'},inplace=True)
print(df)
	Name 	Age	Height
zero	Alex	24	6.0
one	John	40	5.8
two	Renee	26	5.9

Using df.loc, we can still access the row as shown below.

df.loc['zero']
Name      Alex
Age         24
Height       6
Name: zero, dtype: object

2. Pandas access row by index number

To select row by index number, we will have to use df.iloc command...

df.iloc[0]
Name      Alex
Age         24
Height       6
Name: zero, dtype: object

To learn about df.loc() and df.iloc() more, check out following link...

Select Pandas Dataframe Rows And Columns Using iloc loc and ix

Pandas Dataframe Number of Rows

len(df)
3

Pandas Iterate Over Rows

We can use df.iterrows() to loop through Dataframe rows.

for index,row in df.iterrows():
	print(row['Name'])
Alex
John
Renee

Pandas Get Row Number

We can use for loop to print all row numbers.

for index,row in df.iterrows():
	print(index,row['Name'])
zero Alex
one John
two Renee

We can print the row number of a particular row based on condition as well.

df.index[df.Name=='Alex']
Index(['zero'], dtype='object')

Adding Row To Dataframe

Let us say we want to add new row, we can add our 4th row by using following command. Note index name for 4th row can be anything. I used 'three' here.

df.loc['three'] = {'Name':'Paula','Age':55,'Height':5.5}
print(df)
Name 	Age	Height
zero	Alex	24	6.0
one	John	40	5.8
two	Renee	26	5.9
three	Paula	55	5.5

We can also df.append() method.

df.append({'Name':'Karen','Age':21,'Height':5.2},ignore_index=True)

Note: To make the above command work, you will have to use, ignore_index=True. Otherwise you will get following error...

TypeError: Can only append a Series if ignore_index=True or if the Series has a name

Also note, the above command, will remove the custom index names that we created and instead it would create integer values as index as shown below...

	Name 	Age	Height
0	Alex	24	6.0
1	John	40	5.8
2	Renee	26	5.9
3	Paula	55	5.5
4	Karen	21	5.2