3

I have below data frame

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

I want to_html to merge similar value rows and output should be as below:

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

I am currently using below code

 html_str = df.to_html(index=False)

Is there any option to merge rows (like in html we have rows span = n)

Rajesh Mhatre
  • 147
  • 1
  • 1
  • 11

1 Answers1

0

suppose your df looks like this,

    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>'
Pyd
  • 6,017
  • 18
  • 52
  • 109
  • 4
    Thanks for solution, But actually I wanted to merge rows with duplicate data. Solution above just nulls duplicate value. Still By any chance there is any way to merge rows so out put HTML table will be merged rows ? – Rajesh Mhatre Oct 12 '18 at 13:48
  • 1
    This answer doesn't merge rows (as previously stated). For further reference, there is a better answer [here](https://stackoverflow.com/questions/49533330/pandas-data-frame-how-to-merge-columns#answer-49534143) – tgrandje Jan 19 '21 at 09:06