簡體   English   中英

如何使用來自 python pandas 數據幀的適當方程直接生成 latex 表格圖像?

[英]How does one generate latex table images with proper equations from python pandas data frame directly?

Related to my recent question on printing \pm in latex with pandas How to print a literal backslash to get \pm in a pandas data frame to generate a proper error bars in a latex table in python? 我還想顯示正確顯示方程式的表格,但我在表格中得到了文字\pm (+ 它的形狀很奇怪)。

在此處輸入圖像描述

有沒有辦法直接從 python 將我的帶有方程式的數據框轉換為 png latex 並將其保存為圖像?

腳本

import pandas as pd

# data = {'first_column':  ['first_value', 'second_value', ...],
#         'second_column': ['first_value', 'second_value', ...],
#          ....
#         }

import pandas as pd

from uutils import put_pm_to_pandas_data

 data = {
     'Initialization': ['Random',
                        'Random2',
                        ],

     'Test Accuracy': ['0.200+-0.029',
                       '0.200+-0.0',
                       ],
 }

# - to pandas table
df = pd.DataFrame(data)
print(df)

# https://stackoverflow.com/questions/70009242/how-does-one-generate-latex-table-images-with-proper-equations-from-python-panda

# - to latex
data = put_pm_to_pandas_data(data)
df = pd.DataFrame(data)

print(df.to_latex(index=False, escape=False))

import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import table

# ax = plt.subplot(111, frame_on=False) # no visible frame
ax = plt.gca()
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

# table(ax, df)  # where df is your data frame
table(ax, df)  # where df is your data frame

plt.show()

# plt.savefig('mytable.png')

有關的:

您沒有向我們提供put_pm_to_pandas_data的定義。 但這是使用DataFrame.replace的解決方案

import matplotlib.pyplot as plt
import pandas as pd
from pandas.plotting import table

def put_pm_df(df):
    return df.replace("\+-", r"$\pm$", regex=True)
    
data = {
     'Initialization': ['Random',
                        'Random2',
                        ],
     'Test Accuracy': ['0.200+-0.029',
                       '0.200+-0.0',
                       ],
}

df = pd.DataFrame(data)
print(df)

df = put_pm_df(df)
print(df)

print(df.to_latex(index=False, escape=False))

ax = plt.gca()
ax.xaxis.set_visible(False)  # hide the x axis
ax.yaxis.set_visible(False)  # hide the y axis

table(ax, df) 

plt.show()

Output

# initial df

  Initialization Test Accuracy
0         Random  0.200+-0.029
1        Random2    0.200+-0.0

# result of put_pm_df(df)

  Initialization    Test Accuracy
0         Random  0.200$\pm$0.029
1        Random2    0.200$\pm$0.0

# df.to_latex(index=False, escape=False)

\begin{tabular}{ll}
\toprule
Initialization &    Test Accuracy \\
\midrule
        Random &  0.200$\pm$0.029 \\
       Random2 &    0.200$\pm$0.0 \\
\bottomrule
\end{tabular}

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM