繁体   English   中英

将 emacs 组织模式表读入 python pandas Z6A8064B5DF4794505500553C47C5 的优雅方式

[英]Elegant way to read emacs org-mode tables into a python pandas dataframe

使用 python pandas 时,我经常喜欢使用 emacs 组织模式创建表。 要阅读表格,我会执行类似的操作

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 dataframe? 也许还有一种优雅的方法可以将表和 python 源代码保存在同一个组织文件中。

尝试

D = pd.read_csv('file.dat', sep='\s*\|\s*').iloc[:, 1:-1]

这是修改后问题的答案(将表格和源代码保留在 Org 模式文件中)。 我从Quang Hoang 的回答中偷走了 pandas 部分:

* 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)

Here's a source block that initializes the variable `tbl' with the table `foo' above 
and does to it some pandas things as suggested by Quang Hoang in his answer.
To evaluate the code block, press `C-C C-c' in the code block.
You will then get the result below:

  #+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

有关源块的更多信息,请参阅组织手册

编辑:要保留列名(表的第一行),您可以将:colnames no添加到源块 header。 列名本身是在源块中作为tbl[0]获得的,可以在DataFrame构造函数中使用该列名到 label 列如下(nb 与上面相反, DataFrame的一对完整的表是完整的select 的不同方法打印出来,包括您在评论中询问的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 )来添加列名是我从未理解过的:这些天之一,我应该在 Org 模式邮件列表上发布一个关于它的问题......

暂无
暂无

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

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