To print all the rows of a pandas dataframe in python use the iterrows() function. iterrows() is a generator in pandas library that yields both the index and the row of a dataframe.
Method No 1 : Print all the rows of a pandas dataframe in Python using iterrows() function
The best way to print all the rows of pandas dataframe is to use the interrows() function and then get the row and index of the row to print it.
See the following example
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
df = df.reset_index() # make sure indexes pair with number of rows
for index, row in df.iterrows():
print(row['c1'], row['c2'])
But you should also note that Because iterrows returns a Series for each row, it does not preserve dtypes across the rows.” Also, “You should never modify something you are iterating over.
Method No 2: Print all the rows of a pandas dataframe in python using to_string() function
As in the above method we have mentioned that it is not a good idea to use iterrows() function a lot as it is very time-consuming. The other way to print rows of dataframe is to use the to_string() function. In pandas, to_string() function converts a dataframe into a string object which we can then easily print.
See the following example
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
str_df = pd.DataFrame.to_string(df)
print(str_df)
Output of the code
c1 c2
0 10 100
1 11 110
2 12 120
Method No 3: Print all rows of pandas dataframe in python using List Comprehension
List comprehension is just another way to print all the rows of a pandas dataframe. Use the list comprehension method to print all the rows of a pandas dataframe.
See the following Example
import pandas as pd
df = pd.DataFrame({'c1': [10, 11, 12], 'c2': [100, 110, 120]})
# Iterating over one column
result = [x for x in df]
print(result)
# # Iterating over two columns, use `zip`
result = [(x, y) for x, y in zip(df['c1'], df['c2'])]
print(result)
Output of the code
Important note on pandas dataframe interaction method
Iterating through pandas objects is generally slow. In many cases, iterating manually over the rows is not needed.
Summary and conclusion
There are multiple ways you can print all rows of a dataframe in python. Just use the one which suits you. Let me know if you have any questions.
I am a software Engineer having 4+ Years of Experience in Building full-stack applications.