Pandas,to_csv() 到特定格式

1 投票
1 回答
3104 浏览
提问于 2025-04-18 09:29

我想用DecisionTree 2.2.2来建立一个决策树。https://engineering.purdue.edu/kak/distDT/DecisionTree-2.2.2.html

不过,它使用了一种奇怪的csv格式。

"","pgtime","pgstat","age","eet","g2","grade","gleason","ploidy"
"1",6.1,0,64,2,10.26,2,4,"diploid"
"2",9.4,0,62,1,NA,3,8,"aneuploid"
"3",5.2,1,59,2,9.99,3,7,"diploid"
"4",3.2,1,62,2,3.57,2,4,"diploid"
"5",1.9,1,64,2,22.56,4,8,"tetraploid"
"6",4.8,0,69,1,6.14,3,7,"diploid"
"7",5.8,0,75,2,13.69,2,NA,"tetraploid"
"8",7.3,0,71,2,NA,3,7,"aneuploid"
"9",3.7,1,73,2,11.77,3,6,"diploid"
  • 第一行的第一个元素应该是""
  • 表头的名字需要加上引号。
  • 索引列也要加引号。
  • 所有的符号特征都要加引号。

我想知道怎么用pandas的to_csv函数把一个DataFrame保存成这种格式?如果不行的话,有没有什么好的解决办法?

谢谢


这是我尝试过的。我把我的列转换成字符串类型:

df.col1 = df.col1.apply(str) 

然后在保存的时候使用index_label:

df.to_csv( 'filename.csv', header=True, index=True, index_label='"') 

但是这样得到的结果是:

"""",url,class,length,volume,name,degree,pagerank
......

第一个元素是四个引号。

1 个回答

3

首先,想告诉大家,读取这个内容是没问题的:

In [11]: df = pd.read_clipboard(sep=',', index_col=0)

In [12]: df
Out[12]:
   pgtime  pgstat  age  eet     g2  grade  gleason      ploidy
1     6.1       0   64    2  10.26      2        4     diploid
2     9.4       0   62    1    NaN      3        8   aneuploid
3     5.2       1   59    2   9.99      3        7     diploid
4     3.2       1   62    2   3.57      2        4     diploid
5     1.9       1   64    2  22.56      4        8  tetraploid
6     4.8       0   69    1   6.14      3        7     diploid
7     5.8       0   75    2  13.69      2      NaN  tetraploid
8     7.3       0   71    2    NaN      3        7   aneuploid
9     3.7       1   73    2  11.77      3        6     diploid

当你输出CSV文件时,必须使用 quoting=csv.QUOTING_NONNUMERIC*:

In [21]: s = StringIO()

In [22]: df.to_csv(s, quoting=2)  # or output to file instead

In [23]: s.getvalue()
Out[23]: '"","pgtime","pgstat","age","eet","g2","grade","gleason","ploidy"\n1,6.1,0,64,2,10.26,2,4.0,"diploid"\n2,9.4,0,62,1,"",3,8.0,"aneuploid"\n3,5.2,1,59,2,9.99,3,7.0,"diploid"\n4,3.2,1,62,2,3.57,2,4.0,"diploid"\n5,1.9,1,64,2,22.56,4,8.0,"tetraploid"\n6,4.8,0,69,1,6.14,3,7.0,"diploid"\n7,5.8,0,75,2,13.69,2,"","tetraploid"\n8,7.3,0,71,2,"",3,7.0,"aneuploid"\n9,3.7,1,73,2,11.77,3,6.0,"diploid"\n'

* QUOTING_NONNUMERIC 的值是2。

不过,这个结果可能不是你想要的,因为索引列没有被加上引号,我建议你可以修改一下索引:

In [24]: df.index = df.index.astype(str)  # unicode in python 3?

In [25]: s = StringIO()

In [26]: df.to_csv(s, quoting=2)

In [27]: s.getvalue()
Out[27]: '"","pgtime","pgstat","age","eet","g2","grade","gleason","ploidy"\n"1",6.1,0,64,2,10.26,2,4.0,"diploid"\n"2",9.4,0,62,1,"",3,8.0,"aneuploid"\n"3",5.2,1,59,2,9.99,3,7.0,"diploid"\n"4",3.2,1,62,2,3.57,2,4.0,"diploid"\n"5",1.9,1,64,2,22.56,4,8.0,"tetraploid"\n"6",4.8,0,69,1,6.14,3,7.0,"diploid"\n"7",5.8,0,75,2,13.69,2,"","tetraploid"\n"8",7.3,0,71,2,"",3,7.0,"aneuploid"\n"9",3.7,1,73,2,11.77,3,6.0,"diploid"\n'

根据需要进行调整。

撰写回答