1 | initial version |
To display a Pandas Dataframe using a for loop, you can use the iterrows() function to iterate over the rows one by one and print the content. Here is an example:
import pandas as pd
# Create a small dataframe
data = {'Name': ['John', 'Mary', 'Peter'], 'Age': [25, 30, 35], 'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)
# Use a for loop to iterate over the rows and display the content
for index, row in df.iterrows():
print('Name:', row['Name'], '\tAge:', row['Age'], '\tCity:', row['City'])
The output will be:
Name: John Age: 25 City: New York
Name: Mary Age: 30 City: Paris
Name: Peter Age: 35 City: London
Alternatively, you can use the to_string() function with the index=False parameter to display the entire dataframe using a for loop. Here is an example:
import pandas as pd
# Create a small dataframe
data = {'Name': ['John', 'Mary', 'Peter'], 'Age': [25, 30, 35], 'City': ['New York', 'Paris', 'London']}
df = pd.DataFrame(data)
# Use a for loop to display the entire dataframe
for index, row in df.iterrows():
print(row.to_string(index=False))
The output will be:
John 25 New York
Mary 30 Paris
Peter 35 London