Ask Your Question
1

How can you display a Pandas Dataframe using a for loop?

asked 2022-10-31 11:00:00 +0000

lalupa gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2022-02-27 18:00:00 +0000

plato gravatar image

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
edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-10-31 11:00:00 +0000

Seen: 10 times

Last updated: Feb 27 '22