在使用 python pandas 时,我经常喜欢使用 emacs org-mode 创建表。为了阅读表格,我做了类似的事情
import pandas as pd
from numpy import *
D = pd.read_csv('file.dat',sep='|')
D = D.drop(D.columns[0], axis=1)
D = D.drop(D.columns[-1], axis=1)
D = D.rename(columns=lambda x: x.strip())
是否有更优雅(特别是更短)的方法将 org-mode 表读入 pandas 数据帧?也许还有一种优雅的方法可以将表和 python 源代码保存在同一个组织文件中。
这是修改后的问题的答案(将表和源代码保留在 Org 模式文件中)。我从Quang Hoang的回答中偷了熊猫部分:
* foo
Here's a table:
#+NAME: foo
| a | b | c |
|----+-----+------|
| 1 | 1 | 1 |
| 2 | 4 | 8 |
| 3 | 9 | 27 |
| 4 | 16 | 64 |
| 5 | 25 | 125 |
| 6 | 36 | 216 |
| 7 | 49 | 343 |
| 8 | 64 | 512 |
| 9 | 81 | 729 |
| 10 | 100 | 1000 |
#+TBLFM: $2=pow($1, 2) :: $3 = pow($1, 3)
这是一个使用上面的表
tbl
初始化变量 foo
的源代码块
并按照 Quang Hoang 在他的回答中的建议对其进行一些熊猫操作。
要评估代码块,请按代码块中的 C-C C-c
。
然后您将得到以下结果:
#+begin_src python :var tbl=foo :results output
import pandas as pd
D = pd.DataFrame(tbl).iloc[:, 1:-1]
print(D)
#+end_src
#+RESULTS:
#+begin_example
1
0 1
1 4
2 9
3 16
4 25
5 36
6 49
7 64
8 81
9 100
#+end_example
请参阅 Org 手册,了解有关源块的(更多)更多信息。
编辑:要保留列名称(表的第一行),您可以将
:colnames no
添加到源块标题。列名称本身
在源块内获得为 tbl[0]
,并且可以在 DataFrame
构造函数中使用它来标记列,如下所示(注意。与上面相反,DataFrame
是完整的表。我只使用了几个不同的表)选择要打印的部分的方法,包括您在评论中询问的 D.c
方法):
#+begin_src python :var tbl=foo :results output :colnames no
import pandas as pd
D = pd.DataFrame(tbl, columns=tbl[0])
print(D.c)
print("===========")
print(D.iloc[1:, 0:-1])
#+end_src
#+RESULTS:
#+begin_example
0 c
1 1
2 8
3 27
4 64
5 125
6 216
7 343
8 512
9 729
10 1000
Name: c, dtype: object
===========
a b
1 1 1
2 2 4
3 3 9
4 4 16
5 5 25
6 6 36
7 7 49
8 8 64
9 9 81
10 10 100
#+end_example
为什么需要
:colnames no
(而不是:colnames yes
)来添加列名称是我一直不明白的事情:有一天,我应该在组织模式邮件列表上发布一个关于它的问题......
尝试使用
D = pd.read_csv('file.dat', sep='\s*\|\s*').iloc[:, 1:-1]