1

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  
1
  • Try outdf.to_csv(outfile, sep="\t") Haven't tried it, but I think you've just shuffled the parts. Commented May 20, 2014 at 23:44

2 Answers 2

3

.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')
Sign up to request clarification or add additional context in comments.

1 Comment

This is correct and makes sense to me. A csv file for each group was created and correctly delimited. Many thanks
0

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")

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.