[英]How to format `to_latex()` output based on the content of different columns?
我跟進這個問題。 假設我有以下數據框。
df = pd.DataFrame({'col1': [1, 3], 'col2': [2, 1]})
從中我可以得到一張乳膠表
df.to_latex()
我知道我可以為每個 columnm 傳遞一個格式化程序,例如,在上面的問題中。 我的問題是:如何根據col2
的元素格式化col1
的元素,反之亦然?
假設,例如,我想給一個單元格添加一個加號,如果它的值高於相鄰單元格的值,則得到以下結果。
\begin{tabular}{lrr}
\toprule
{} & col1 & col2 \\
\midrule
0 & 1 & +2 \\
1 & +3 & 1 \\
\bottomrule
\end{tabular}
看起來formatters
只接受處理單元格值的函數,而沒有關於數據幀索引/列的任何信息。 所以它可能不適合你的目的。
我會預先格式化數據並傳遞給to_latex
:
strs = np.array([['','+']]* len(df))
signs = np.where(df['col1'].lt(df['col2']).values[:,None], strs,strs[:,::-1])
(signs + df.astype(str)).to_latex()
輸出:
\begin{tabular}{lll}
\toprule
{} & col1 & col2 \\
\midrule
0 & 1 & +2 \\
1 & +3 & 1 \\
\bottomrule
\end{tabular}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.