在不删除逗号的情况下将数据帧写入csv [英] Writing dataframe to csv WITHOUT removing commas

查看:63
本文介绍了在不删除逗号的情况下将数据帧写入csv的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将pandas数据框写入csv. df的列之一具有条目,这些条目是列表,例如[1,2],[3,4],...

I want to write a pandas dataframe to csv. One of the columns of the df has entries which are lists, e.g. [1, 2], [3, 4], ...

当我使用df.to_csv('output.csv')并打开输出csv文件时,逗号消失了.也就是说,csv的相应列具有条目[1 2],[3 4],....

When I use df.to_csv('output.csv') and I open the output csv file, the commas are gone. That is, the corresponding column of the csv has entries [1 2], [3 4], ....

是否有一种方法可以在不删除这些列表中的逗号的情况下将数据帧写入csv?我也尝试过使用csv.writer.

Is there a way to write a dataframe to csv without removing the commas in these lists? I've also tried using csv.writer.

推荐答案

添加关键字参数quoting=csv.QUOTE_ALL:

import csv
import pandas as pd

data = {"A": [1,2,3], "B": [[11,12],[21,22],[31,32]]}
df = pd.DataFrame(data)
df.index.name='index'

# df
#        A         B
# index             
# 0      1  [11, 12]
# 1      2  [21, 22]
# 2      3  [31, 32]

df.to_csv('test.csv',quoting=csv.QUOTE_ALL)

输出:

"index","A","B"
"0","1","[11, 12]"
"1","2","[21, 22]"
"2","3","[31, 32]"

这篇关于在不删除逗号的情况下将数据帧写入csv的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆