在此处打印要在 markdown 中使用的数据框

问题描述 投票:0回答:1

我想将数据帧打印到 Markdown 并在此处的 Markdown 中使用它。

我看到了 to_markdown() api,但该格式在 markdown 中不起作用。

所以我尝试下面的代码,它工作正常:

import pandas as pd

def dumpmd(df):
    out = []
    out.append("|".join(df.columns))
    r = []
    for name in df.columns:
        r.append(":-")
    out.append("|".join(r))    
    for i,row in df.iterrows():
        r = []
        r1 = []
        for e in row:
            r.append(str(e))
        out.append("|".join(r))
    out = "\n".join(out)
    return out


data = [['1','B','C'],
    ['2','E','F'],
    ['3','H','I']]


df = pd.DataFrame(data,columns=["C1" ,"C2","C3"])

print(df.to_markdown(tablefmt='pipe',index=False))
print(dumpmd(df))

输出:

| C1 | C2 | C3 |
|----+----+----|
|  1 | B  | C  |
|  2 | E  | F  |
|  3 | H  | I  |
C1|C2|C3
:-|:-|:-
1|B|C
2|E|F
3|H|I

有人可以帮助简化此代码或任何更好的解决方案来从数据帧输出预期的降价表吗?

python pandas markdown
1个回答
0
投票

也许尝试制表

代码:

import pandas as pd
from tabulate import tabulate


data = {"spam": [1, 2, 3], "ham": [4, 5, 6]}
df = pd.DataFrame(data=data)
mark_down_df = tabulate(tabular_data=df, tablefmt="github", headers="keys", showindex=False)
print(mark_down_df)

输出:

|   spam |   ham |
|--------|-------|
|      1 |     4 |
|      2 |     5 |
|      3 |     6 |
© www.soinside.com 2019 - 2024. All rights reserved.