繁体   English   中英

Pandas,to_csv()为特定格式

[英]Pandas, to_csv () to a specific format

我想使用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
......

第一个元素是四个引号。

首先只是为了证明,阅读这是好的:

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'

按要求。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM