Pandas,to_csv()为特定格式

时间:2014-06-11 21:29:18

标签: python pandas

我想使用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 个答案:

答案 0 :(得分: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'

根据需要。