如何在熊猫to_html中创建合并的行

时间:2018-10-12 11:59:34

标签: python html pandas dataframe

我在数据框下方

UK | FOOD  | Sales | 4000
UK | FOOD  | Order | 6000
US | DRINK | Sales | 4300
US | DRINK | Order | 6600

我要to_html合并相似值的行 并输出如下:

UK | FOOD  | Sales | 4000
           | Order | 6000 
US | DRINK | Sales | 4300
           | Order | 6500

我当前正在使用以下代码

 html_str = df.to_html(index=False)

是否有任何合并行的选项(例如在html中,我们有span = n的行)

1 个答案:

答案 0 :(得分:2)

假设您的df看起来像这样,

    A   B       C       D
0   UK  FOOD    Sales   4000
1   UK  FOOD    Order   6000
2   US  DRINK   Sales   4300
3   US  DRINK   Order   6600

df.loc[df.duplicated(subset=['A','B']),['A','B']]=''
#   A   B       C       D
#   UK  FOOD    Sales   4000
#               Order   6000
#   US  DRINK   Sales   4300
#               Order   6600

html_str=df.to_html(index=False)

#print(html_str)
#'<table border="1" class="dataframe">\n  <thead>\n    <tr style="text-align: right;">\n      <th>A</th>\n      <th>B</th>\n      <th>C</th>\n      <th>D</th>\n    </tr>\n  </thead>\n  <tbody>\n    <tr>\n      <td>UK</td>\n      <td>FOOD</td>\n      <td>Sales</td>\n      <td>4000</td>\n    </tr>\n    <tr>\n      <td></td>\n      <td></td>\n      <td>Order</td>\n      <td>6000</td>\n    </tr>\n    <tr>\n      <td>US</td>\n      <td>DRINK</td>\n      <td>Sales</td>\n      <td>4300</td>\n    </tr>\n    <tr>\n      <td></td>\n      <td></td>\n      <td>Order</td>\n      <td>6600</td>\n    </tr>\n  </tbody>\n</table>'