Kayla Schwoerer
Kayla Schwoerer

Reputation: 3

Export DataFrame from Python to CSV

I have a data frame I created with my original data appended with the topics from topic modeling. I keep running into errors when trying to export the data table into csv.

I've tried both csv module and pandas but get errors from both.

The data table has 1765 rows so writing the file row by row is not really an option.

When using pandas, most common errors are

DataFrame constructor not properly called!

and

function object has no attribute 'to_csv'

Code used:

import pandas as pd

data = (before.head)

df = pd.DataFrame(before.head)
df.to_csv (r'C:\Users\***\Desktop\beforetopics.csv', index = False, header=True)
print (df)

For the CSV module, there have been several errors such as

iterable expected, not method

Basically, how do I export this table (screenshot attached) into a csv file?

Screenshot of Table

Upvotes: 0

Views: 20201

Answers (2)

Karina Kozarova
Karina Kozarova

Reputation: 1205

You can use the to_csv function:

before.to_csv('file_name.csv')

If you need extra options, you can check the documentation from here.

Upvotes: 1

Vijay
Vijay

Reputation: 134

What is the command that you're trying to run?

Try this:

dataframe.to_csv('file_name.csv')

Or if it is the unicode error that you're coming across,

Try this:

dataframe.to_csv('file_name.csv', header=True, index=False, encoding='utf-8')

Since your dataframe's name is before,

Try this:

before.to_csv('file_name.csv', header=True, index=False, encoding='utf-8')

Upvotes: 1

Related Questions