如何将漂亮打印的数据框读入Pandas数据框?

问题描述

# necessary imports
from tabulate import tabulate
import pandas as pd

我有一个dataframe

df = pd.DataFrame({'A': ['A0','A1','A2','A3'],'B': ['B0','B1','B2','B3'],'C': ['C0','C1','C2','C3'],'D': ['D0','D1','D2','D3']},index=[0,1,2,3])

使用this,我很喜欢打印它:

prettyprint=tabulate(df,headers='keys',tablefmt='psql')
print(prettyprint)

结果:

+----+-----+-----+-----+-----+
|    | A   | B   | C   | D   |
|----+-----+-----+-----+-----|
|  0 | A0  | B0  | C0  | D0  |
|  1 | A1  | B1  | C1  | D1  |
|  2 | A2  | B2  | C2  | D2  |
|  3 | A3  | B3  | C3  | D3  |
+----+-----+-----+-----+-----+

Saving转换为文本文件

with open("PrettyPrintOutput.txt","w") as text_file:
    text_file.wite(prettyprint)

如何在不手动进行大量文本处理的情况下将PrettyPrintOutput.txt读回到dataframe

解决方法

一种解决方案是在pd.read_csv / pd.read_clipboard中使用聪明的关键字参数:

    df = pd.read_csv(r'PrettyPrintOutput.txt',sep='|',comment='+',skiprows=[2],index_col=1)
    df = df[[col for col in df.columns if 'Unnamed' not in col]]

我只是将所有以'+'开头的行定义为注释,因此不会导入它们。这不利于第三行,必须使用跳过行将其排除。

第二行是必需的,因为您使用'|'结束了其他列作为分隔符。如果您事先知道列名,请使用关键字usecols来明确。

输出:

       A      B      C      D   
                                
0      A0     B0     C0     D0  
1      A1     B1     C1     D1  
2      A2     B2     C2     D2  
3      A3     B3     C3     D3 

它也可以与pd.read_clipboard一起使用,因为这些函数接受相同的关键字参数。