Wednesday, January 15, 2025
HomeTechHow do you write a pandas DataFrame to a CSV file in...

How do you write a pandas DataFrame to a CSV file in Python?

Here’s a simple guide on how to write a Pandas DataFrame to a CSV file in Python, formatted for easy copying and pasting into a website:

Writing a Pandas DataFrame to a CSV File

python
import pandas as pd

# Create a sample DataFrame
data = {
'Column1': [1, 2, 3],
'Column2': ['A', 'B', 'C'],
'Column3': [4.1, 5.2, 6.3]
}

df = pd.DataFrame(data)

# Write DataFrame to CSV
df.to_csv('output.csv', index=False)

Explanation:

  • import pandas as pd: Imports the Pandas library.
  • data: Creates a dictionary with sample data.
  • pd.DataFrame(data): Converts the dictionary to a DataFrame.
  • df.to_csv('filename.csv', index=False): Writes the DataFrame to a CSV file.

This can be easily copied and pasted into a code block on a website!

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x