use*_*068 5 python dataframe pandas
这是一个简单的问题,很难在网上找到答案。情况如下:
>>> A
[('hey', 'you', 4), ('hey', 'not you', 5), ('not hey', 'you', 2), ('not hey', 'not you', 6)]
>>> A_p = pandas.DataFrame(A)
>>> A_p
0 1 2
0 hey you 4
1 hey not you 5
2 not hey you 2
3 not hey not you 6
>>> B_p = A_p.pivot(0,1,2)
>>> B_p
1 not you you
0
hey 5 4
not hey 6 2
Run Code Online (Sandbox Code Playgroud)
这与文档中的建议不完全相同,在pivot此处显示的结果左上角没有1和0。这就是我想要的,一个打印为
not you you
hey 5 4
not hey 6 2
Run Code Online (Sandbox Code Playgroud)
问题是正常行为导致csv文件的第一行是
0,not you,you
Run Code Online (Sandbox Code Playgroud)
当我真的想要
not you, you
Run Code Online (Sandbox Code Playgroud)
当普通的csv文件(带有前面的“ 0”)读入R时,它没有正确设置框架对象的列名和行名,从而导致了繁琐的手动操作,以正确的格式获取它。有没有办法让我获得DataFrame对象,而在左上角没有该附加信息呢?
好吧,你有:
In [17]: B_p.to_csv(sys.stdout)
0,not you,you
hey,5.0,4.0
not hey,6.0,2.0
In [18]: B_p.to_csv(sys.stdout, index=False)
not you,you
5.0,4.0
6.0,2.0
Run Code Online (Sandbox Code Playgroud)
但我假设您想要行名称。将索引名称设置为 None ( B_p.index.name = None) 会给出一个前导逗号:
In [20]: B_p.to_csv(sys.stdout)
,not you,you
hey,5.0,4.0
not hey,6.0,2.0
Run Code Online (Sandbox Code Playgroud)
这大致匹配(忽略带引号的字符串)R 中写入的write.csv内容row.names=TRUE:
"","a","b"
"foo",0.720538259472741,-0.848304940318957
"bar",-0.64266667412325,-0.442441171401282
"baz",-0.419181615269841,-0.658545964124229
"qux",0.881124313748992,0.36383198969179
"bar2",-1.35613767310069,-0.124014006180608
Run Code Online (Sandbox Code Playgroud)
这些有帮助吗?
编辑:index_label=False今天添加了执行您想要的操作的选项:
In [2]: df
Out[2]:
A B
one 1 4
two 2 5
three 3 6
In [3]: df.to_csv('foo.csv', index_
index_exp index_label= index_name=
In [3]: df.to_csv('foo.csv', index_name=False)
In [4]:
11:24 ~/code/pandas (master)$ R
R version 2.14.0 (2011-10-31)
Copyright (C) 2011 The R Foundation for Statistical Computing
ISBN 3-900051-07-0
Platform: x86_64-unknown-linux-gnu (64-bit)
R is free software and comes with ABSOLUTELY NO WARRANTY.
You are welcome to redistribute it under certain conditions.
Type 'license()' or 'licence()' for distribution details.
Natural language support but running in an English locale
R is a collaborative project with many contributors.
Type 'contributors()' for more information and
'citation()' on how to cite R or R packages in publications.
Type 'demo()' for some demos, 'help()' for on-line help, or
'help.start()' for an HTML browser interface to help.
Type 'q()' to quit R.
[Previously saved workspace restored]
re> read.csv('foo.csv')
A B
one 1 4
two 2 5
three 3 6
Run Code Online (Sandbox Code Playgroud)