是否有相当于 to_markdown 的读取数据?

div*_*obi 5 python pandas

使用 pandas 1.0.0.to_markdown()在本论坛中以降价方式显示数据框内容的使用将会激增。有没有一种方便的方法将数据加载回数据帧?也许是一个选择.from_clipboard(markdown=True)

Dav*_*ave 9

您可以使用 pandasread_table函数读取降价表(或任何结构化文本表):

让我们创建一个示例降价表:

pd.DataFrame({"a": [0, 1], "b":[2, 3]}).to_markdown()                                                                                                                                                    
Run Code Online (Sandbox Code Playgroud)
|    |   a |   b |
|---:|----:|----:|
|  0 |   0 |   2 |
|  1 |   1 |   3 |
Run Code Online (Sandbox Code Playgroud)

如您所见,这只是一个结构化文本表,其中分隔符是管道,有很多空白,最左侧和最右侧有空列,并且有一个必须删除的标题下划线。

pd
  # Read a markdown file, getting the header from the first row and inex from the second column
  .read_table('df.md', sep="|", header=0, index_col=1, skipinitialspace=True)
  # Drop the left-most and right-most null columns 
  .dropna(axis=1, how='all')
  # Drop the header underline row
  .iloc[1:]   

   a  b
0  0  2
1  1  3
Run Code Online (Sandbox Code Playgroud)

  • 如果您有一个格式漂亮的表,则列名中可能会有空格。您可以使用“df.columns = df.columns.str.strip()”来摆脱它。 (5认同)

joe*_*lom 5

这将负责删除值和列名称中的所有空格(因此,如果您想在值中保留空格,请务必小心):

from io import StringIO
import pandas as pd

md_table = pd.DataFrame({"a": [3, 10000], "b":[2222, 3]}).to_markdown()
print(md_table)
Run Code Online (Sandbox Code Playgroud)
# The white space on both columns and values need to be removed
|    |     a |    b |
|---:|------:|-----:|
|  0 |     3 | 2222 |
|  1 | 10000 |    3 |
Run Code Online (Sandbox Code Playgroud)
# The white space on both columns and values need to be removed
|    |     a |    b |
|---:|------:|-----:|
|  0 |     3 | 2222 |
|  1 | 10000 |    3 |
Run Code Online (Sandbox Code Playgroud)
       a     b
0      3  2222
1  10000     3
Run Code Online (Sandbox Code Playgroud)


div*_*obi 3

到目前为止,没有一个答案从剪贴板读取数据。它们都要求数据位于字符串中。这导致我查看了 的源代码pandas.read_clipboard(),你瞧,该方法内部使用pandas.read_csv(), 并将所有参数传递给它。这会自动产生以下解决方案:

t = pd.DataFrame({"a": [0, 1], "b":[2, 3]}).to_markdown()                                                                                                                                                    
print(t)
Run Code Online (Sandbox Code Playgroud)
|    |   a |   b |
|---:|----:|----:|
|  0 |   0 |   2 |
|  1 |   1 |   3 |
Run Code Online (Sandbox Code Playgroud)

标记表格并将其复制到剪贴板(Windows 上为 Ctrl-C)。基于上述答案:

|    |   a |   b |
|---:|----:|----:|
|  0 |   0 |   2 |
|  1 |   1 |   3 |
Run Code Online (Sandbox Code Playgroud)

下一步是将其集成到https://pyjanitor-devs.github.io/pyjanitor/中,以便可以使用参数轻松调用它markdown=True