Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

เขียนโปรแกรม Python แปลง DataFrame ที่กำหนดเป็นเอกสาร LaTeX


สมมติ คุณมี DataFrame และผลลัพธ์สำหรับการแปลงเป็น LaTeX คือ

\begin{tabular}{lrr}
\toprule
{} &   Id &   Age \\
\midrule
0 &    1 &    12 \\
1 &    2 &    13 \\
2 &    3 &    14 \\
3 &    4 &    15 \\
4 &    5 &    16 \\
\bottomrule
\end{tabular}

Solution

เพื่อแก้ปัญหานี้ เราจะทำตามขั้นตอนด้านล่าง −

  • กำหนด DataFrame

  • ใช้ฟังก์ชัน to_latex() บน DataFrame และตั้งค่า Index และ Multirow เป็น True คือ ด้านล่าง

df.to_latex(index = True, multirow = True)

ตัวอย่าง

import pandas as pd
df = pd.DataFrame({'Id': [1,2,3,4,5],
                    'Age': [12,13,14,15,16]})
print(df.to_latex(index = True, multirow = True))

ผลลัพธ์

\begin{tabular}{lrr}
\toprule
{} &   Id &   Age \\
\midrule
0 &    1 &    12 \\
1 &    2 &    13 \\
2 &    3 &    14 \\
3 &    4 &    15 \\
4 &    5 &    16 \\
\bottomrule
\end{tabular}