writing a csv file by column in pandas throws error

12k views Asked by At

I am reading and writing a csv file using pandas.

I am reading a csv file column by column and writing it to a seperate csv file by column by column reading works fine but while writing a csv file it thorws error

import pandas
f1 = open('artist_links','a')
data_df = pandas.read_csv('upc1.upcs_result.csv')
#data_wr = pandas.to_csv('test.csv')

df = data_df['one']
dd = data_df['two']
header = ["df", "dd"]
df.to_csv("test.csv",columns = header)

Output:

Traceback (most recent call last):
  File "merge.py", line 9, in <module>
    df.to_csv("test.csv",columns = header)
TypeError: to_csv() got an unexpected keyword argument 'columns'

But there is a column argument actully here pandas library

How could i make this program work(Writing column by column)

1

There are 1 answers

5
Alex Huszagh On

Changes in v0.16.0

http://pandas.pydata.org/pandas-docs/dev/whatsnew.html

cols as the keyword for the csv and Excel writers was replaced with columns.

Try cols instead or upgrade pandas.

Instead of:

df.to_csv("test.csv", columns=header)

Use:

df.to_csv("test.csv", cols=header)

Edit: Either way you should upgrade. Sincerely. If the error is a keyword argument and you are basing your method off of documentation for the most recent version on software written over 1.5 years ago, with substantial changes made since then, you should upgrade.

EDIT2: If you're desperate to make life difficult for yourself and continue using outdated functions and try to use new features, you could do workarounds. This is not recommended, since some stuff may be a lot more subtle and throw exceptions when you least expect it.

You could... do...

lst = []
for column in header:
    s = df[column]
    # export all to list and nested
    lst.append(s.tolist())
# zip resulting lists to tuples
zipped = zip(*lst)
# export them as a CSV.
print '\n'.join([','.join(i) for i in zipped])

EDIT3: Much simpler, but you could also do:

df2 = df[header]   # return copy
df2.to_csv()