cubedNnoobed
cubedNnoobed

Reputation: 135

Unable to create csv files from Pandas DataFrame using to_csv() method

I have a DataFrame df which I have grouped according to an attribute. I am trying to write each group to a csv file of its own. I have tried using the pandas.DataFrame.to_csv() method. I get the following error.

outcsv = pd.DataFrame.to_csv(outdf, sep = "\t")         
TypeError: to_csv() takes at least 2 arguments (2 given)

The code I am using is the following.

def groupChromosomes(filepath, groupbykey, sep):
import csv
import pandas as pd
df = pd.read_csv(filepath, sep = sep )
d2 = df.groupby(groupbykey)
for name, group in d2:
    with open(name+'.csv', 'w') as outfile:
        outdf = pd.DataFrame(group)     
        #print outdf
        outcsv = pd.DataFrame.to_csv(outdf, sep = "\t")         
        return outcsv  

Upvotes: 1

Views: 3806

Answers (2)

user3654387
user3654387

Reputation: 2330

I'm not seeing an output path and/or filename, which should be the first argument. I think this is why it is choking as its not seeing the first required input. It looks like you are passing it a pandas dataframe as the first item. Look here - http://pandas.pydata.org/pandas-docs/version/0.13.1/generated/pandas.DataFrame.to_csv.html

So it should be something like:

outdf.to_csv('path\to\file', sep="\t")

Upvotes: 0

Marius
Marius

Reputation: 60060

.to_csv() is a method of dataframe objects, so you should be calling it from the object you want to export. Also, you don't really want to return it from a function, since all the method does is write the file.

Your loop should look like:

for name, group in d2:
    # I'm not even sure if this step is necessary, you should
    # probably be able to do group.to_csv() directly 
    outdf = pd.DataFrame(group)
    outdf.to_csv(name + '.csv', sep='\t')

Upvotes: 3

Related Questions