【问题标题】:How to correctly write out a TSV file from a series in Pandas?如何从 Pandas 的系列中正确写出 TSV 文件?
【发布时间】:2016-09-17 01:59:22
【问题描述】:

我已阅读手册here 并看到this 的答案,但它不起作用:

>>> import pandas as pd
>>> import csv
>>> pd.Series([my_list]).to_csv('output.tsv',sep='\t',index=False,header=False, quoting=csv.QUOTE_NONE)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: to_csv() got an unexpected keyword argument 'quoting'

没有引用参数,它可以工作。

pd.Series([my_list]).to_csv('output.tsv',sep='\t',index=False,header=False)

但这与我的预期用途不兼容。

为了让事情更加混乱,当我这样写一个表格时,没有引号,也没有错误:

my_dataframe.to_csv('output2.tsv',sep='\t', quoting=csv.QUOTE_NONE)

知道发生了什么吗?

【问题讨论】:

  • 根据docs,Series.to_csv 没有quoting 参数,因此您收到该错误也就不足为奇了。你有什么理由不能只使用DataFrame
  • 我只是想写出单列数据,并认为可以避免不必要的转换步骤。毕竟转换为DataFrame 是必要的。没什么大不了的,我只会这样做。谢谢。

标签: python pandas dataframe


【解决方案1】:

internal pandas implementation of Series.to_csv()首先将Series转换为DataFrame,然后调用DataFrame.to_csv()方法:

def to_csv(self, path, index=True, sep=",", na_rep='', float_format=None,
           header=False, index_label=None, mode='w', nanRep=None,
           encoding=None, date_format=None, decimal='.'):
    """
    Write Series to a comma-separated values (csv) file
    ...
    """
    from pandas.core.frame import DataFrame
    df = DataFrame(self)
    # result is only a string if no path provided, otherwise None
    result = df.to_csv(path, index=index, sep=sep, na_rep=na_rep,
                       float_format=float_format, header=header,
                       index_label=index_label, mode=mode, nanRep=nanRep,
                       encoding=encoding, date_format=date_format,
                       decimal=decimal)
    if path is None:
        return result

所以你可以自己转换,然后你会有更丰富的参数集:

pd.DataFrame(your_series_obj).to_csv(..., quoting=csv.QUOTE_NONE)

或:

your_series_obj.to_frame().to_csv(..., quoting=csv.QUOTE_NONE)

【讨论】:

    猜你喜欢
    • 2023-03-11
    • 1970-01-01
    • 2021-05-02
    • 2018-12-13
    • 2017-12-12
    • 2012-03-28
    • 2018-08-26
    • 2023-03-22
    • 1970-01-01
    相关资源
    最近更新 更多