【问题标题】:In Pandas to_csv function, i need to modify the seperator only for the header to ":"在 Pandas to_csv 函数中,我只需要将标题的分隔符修改为“:”
【发布时间】:2019-05-26 12:45:34
【问题描述】:

在熊猫数据框上执行“to_csv”时,仅将标题分隔符更改为“:”的最佳方法是什么?

例如:

items = [['Phone', 2000, 'Apple'], ['TV', 1500, 'LG'], ['Radio', 800, 'FM'], ['Fridge',0,'LG']]  
df = pd.DataFrame(items, columns=['Item', 'Price', 'Model'], dtype=float)  
print(df) 


     Item   Price  Model
0   Phone  2000.0  Apple
1      TV  1500.0     LG
2   Radio   800.0     FM
3  Fridge     0.0     LG

当我将其转换为 CSV 时,我得到了

df.to_csv(index=False)

输出

'Item,Price,Model\nPhone,2000.0,Apple\nTV,1500.0,LG\nRadio,800.0,FM\nFridge,0.0,LG\n'

相反,我希望输出为:

'Item:Price:Model\nPhone,2000.0,Apple\nTV,1500.0,LG\nRadio,800.0,FM\nFridge,0.0,LG\n'

【问题讨论】:

  • 可能是df.to_csv(sep=":", index=False)

标签: python pandas python-2.7 csv


【解决方案1】:

它似乎不支持它,因为底层的 CSV 编写器将标题视为任何其他行。

以下 sn-p 有效,但失去了to_csv 的原子性。

In [1]: import pandas as pd

In [2]: items = [['Phone', 2000, 'Apple'], ['TV', 1500, 'LG'], ['Radio', 800, 'FM'], ['Fridge',0,'LG']]
   ...: df = pd.DataFrame(items, columns=['Item', 'Price', 'Model'], dtype=float)

In [3]: with open('out.csv', 'w') as f:
   ...:     f.write(':'.join(df.columns) + '\n')

In [4]: df.to_csv('out.csv', mode='a', header=False)

In [5]: !cat out.csv
Item:Price:Model
0,Phone,2000.0,Apple
1,TV,1500.0,LG
2,Radio,800.0,FM
3,Fridge,0.0,LG

【讨论】:

  • 请注意,此解决方案会打开和关闭文件两次,这不是绝对必要的。您可以在单个 with 语句中完成所有操作。
  • 没错,忘了to_csv支持这个
【解决方案2】:

Pandas to_csv 不支持标题与数据的不同分隔符。您可以改用标准库中的 csv 模块:

import csv

with open('file.csv', 'w', newline='') as fout:
    writer = csv.writer(fout, delimiter=':')  # define writer object for header output
    writer.writerow(df.columns)  # writerow accepts any iterable of strings or numbers
    df.to_csv(fout, header=False, index=False)  # comma delimiter is default

结果:

Item:Price:Model
Phone,2000.0,Apple
TV,1500.0,LG
Radio,800.0,FM
Fridge,0.0,LG

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-09-05
    • 1970-01-01
    • 2018-10-08
    • 2013-11-23
    • 2019-04-17
    • 1970-01-01
    • 2018-12-22
    • 1970-01-01
    相关资源
    最近更新 更多