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
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-10-31 11:00:00 +0000
Seen: 10 times
Last updated: Feb 27 '22
What steps do I need to take to present a pandas DataFrame on a Django template?
How can I create a pandas dataframe using several OR operators in the statement?
What is the issue with the .display() function on a Pandas DataFrame in PySpark on Databricks?
How can we bring googlesheets data into a pyspark dataframe?
How can a portion of a file name be retrieved and stored in a DataFrame using Pandas?
How can we perform aggregate functions on particular datetime values in a Pandas DataFrame?
How do you update a dataframe within a for loop in R after passing a list?
What is the method for computing the overall sum of a dataframe, excluding a singular row?