在 Pandas 中按列写入 csv 文件会引发错误

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30749022/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-13 23:27:16  来源:igfitidea点击:

writing a csv file by column in pandas throws error

pythoncsvpandaspandas-datareader

提问by Mounarajan

I am reading and writing a csv file using pandas.

我正在使用 Pandas 读取和写入 csv 文件。

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

我正在逐列读取 csv 文件,然后逐列将其写入单独的 csv 文件,读取工作正常,但在写入 csv 文件时,它引发错误

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

但是实际上这里有一个列参数pandas library

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

我怎样才能使这个程序工作(逐列编写)

回答by Alexander Huszagh

Changes in v0.16.0

v0.16.0 的变化

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

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

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

cols 作为 csv 和 Excel 编写器的关键字已替换为列。

Try cols instead or upgrade pandas.

尝试使用 cols 或升级 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.

编辑:无论哪种方式,您都应该升级。真挚地。如果错误是关键字参数,并且您的方法基于 1.5 年前编写的软件的最新版本的文档,从那时起进行了重大更改,则您应该升级。

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.

EDIT2:如果你不顾一切地让自己的生活变得困难并继续使用过时的功能并尝试使用新功能,你可以做一些解决方法。不推荐这样做,因为有些东西可能更微妙,并在您最不期望的时候抛出异常。

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:

EDIT3:简单得多,但你也可以这样做:

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