Nice programing

팬더 데이터 프레임 예쁜 인쇄

nicepro 2020. 10. 18. 19:35
반응형

팬더 데이터 프레임 예쁜 인쇄


다음과 같이 pandas 데이터 프레임을 멋진 텍스트 기반 테이블로 어떻게 인쇄 할 수 있습니까?

+------------+---------+-------------+
| column_one | col_two |   column_3  |
+------------+---------+-------------+
|          0 |  0.0001 | ABCD        |
|          1 |  1e-005 | ABCD        |
|          2 |  1e-006 | long string |
|          3 |  1e-007 | ABCD        |
+------------+---------+-------------+

저는 그 요구에 맞는 훌륭한 도구를 찾았습니다 . tabulate 라고 합니다.

표 형식의 데이터를 인쇄하고 DataFrame.

from tabulate import tabulate
import pandas as pd

df = pd.DataFrame({'col_two' : [0.0001, 1e-005 , 1e-006, 1e-007],
                   'column_3' : ['ABCD', 'ABCD', 'long string', 'ABCD']})
print(tabulate(df, headers='keys', tablefmt='psql'))

+----+-----------+-------------+
|    |   col_two | column_3    |
|----+-----------+-------------|
|  0 |    0.0001 | ABCD        |
|  1 |    1e-05  | ABCD        |
|  2 |    1e-06  | long string |
|  3 |    1e-07  | ABCD        |
+----+-----------+-------------+

노트 :

모든 유형의 데이터에 대한 행 인덱스를 제외하려면 showindex="never"또는을 전달하십시오 showindex=False.


prettytable 을 사용하여 테이블을 텍스트로 렌더링 할 수 있습니다 . 트릭은 data_frame을 메모리 내 csv 파일로 변환하고 꽤 잘 읽도록하는 것입니다. 코드는 다음과 같습니다.

from StringIO import StringIO
import prettytable    

output = StringIO()
data_frame.to_csv(output)
output.seek(0)
pt = prettytable.from_csv(output)
print pt

나는 잠시 동안 Ofer의 대답을 사용했으며 대부분의 경우 훌륭하다는 것을 알았습니다. 안타깝게도 pandas의 to_csvprettytable 의 from_csv 사이 불일치로 인해 prettytable을 다른 방식으로 사용해야했습니다.

실패 사례 중 하나는 쉼표가 포함 된 데이터 프레임입니다.

pd.DataFrame({'A': [1, 2], 'B': ['a,', 'b']})

Prettytable은 다음과 같은 형식의 오류를 발생시킵니다.

Error: Could not determine delimiter

다음 함수는이 경우를 처리합니다.

def format_for_print(df):    
    table = PrettyTable([''] + list(df.columns))
    for row in df.itertuples():
        table.add_row(row)
    return str(table)

색인에 관심이 없으면 다음을 사용하십시오.

def format_for_print2(df):    
    table = PrettyTable(list(df.columns))
    for row in df.itertuples():
        table.add_row(row[1:])
    return str(table)

간단한 접근 방식은 pandas가 즉시 수행 하는 html로 출력하는 것입니다 .

df.to_html('temp.html')

Jupyter 노트북을 사용하는 경우 다음 코드를 실행하여 올바른 형식의 테이블에 데이터 프레임을 대화식으로 표시 할 수 있습니다.

이 답변은 위의 to_html ( 'temp.html') 답변을 기반으로하지만 파일을 만드는 대신 노트북에 올바른 형식의 테이블을 직접 표시합니다.

from IPython.display import display, HTML

display(HTML(df.to_html()))

이 코드에 대한 크레딧 : iPython Notebook의 테이블로 DataFrame 표시


Following up on Mark's answer, if you're not using Jupyter for some reason, e.g. you want to do some quick testing on the console, you can use the DataFrame.to_string method, which works from -- at least -- Pandas 0.12 (2014) onwards.

import pandas as pd

matrix = [(1, 23, 45), (789, 1, 23), (45, 678, 90)]
df = pd.DataFrame(matrix, columns=list('abc'))
print(df.to_string())

#  outputs:
#       a    b   c
#  0    1   23  45
#  1  789    1  23
#  2   45  678  90

I wanted a paper printout of a dataframe but I wanted to add some results and comments as well on the same page. I have worked through the above and I could not get what I wanted. I ended up using file.write(df1.to_csv()) and file.write(",,,blah,,,,,,blah") statements to get my extras on the page. When I opened the csv file it went straight to a spreadsheet which printed everything in the right pace and format.

참고URL : https://stackoverflow.com/questions/18528533/pretty-printing-a-pandas-dataframe

반응형