vestland
vestland

Reputation: 61074

How to produce simple html readable format of pandas dataframe?

With a pandas dataframe such as this:

enter image description here

I would like to produce a string viewable in html format like this:

A: alfa 1, alfa 2
B: beta 1, beta 2

Which means that my actual string would have to look something like:

'A: alfa info 1, alfa info 2<br>B beta info 1 beta info 2'

I'd like to accomplish this with a nested list comprehension, and I've tried variatons of:

[[c + ': ' + r for r in df[c]] for c in df.columns]

Which gives:

[['A: alfa 1', 'A: alfa 2'], ['B: beta 1', 'B: beta 2']]

I'm unable to get the c component 'outside' the list with row values, and in any case I'm a bit lost on how to get to the next step of unlisting these items into a string.

I'm a bit surprised that there's no built-in way to do this, since numerous other string-related methods exist like df.do_dict, df.to_string and df.to_html, none of which returns the desired output.

Thank you for any suggestions!

Reproducible example

import pandas as pd
df=pd.DataFrame({'A': ['alfa 1', 'alfa 2'],
                 'B': ['beta 1', 'beta 2']})

Upvotes: 0

Views: 234

Answers (4)

buran
buran

Reputation: 14233

Most straight-forward approach is to transpose the DataFrame and then use DataFrame.to_html():

import pandas as pd
df=pd.DataFrame({'A': ['alfa 1', 'alfa 2'],
                 'B': ['beta 1', 'beta 2']})

df = df.transpose()
df.to_html('test.html', header=False, border=0)

Note, this will produce table with border 0

<table border="0" class="dataframe">
  <tbody>
    <tr>
      <th>A</th>
      <td>alfa 1</td>
      <td>alfa 2</td>
    </tr>
    <tr>
      <th>B</th>
      <td>beta 1</td>
      <td>beta 2</td>
    </tr>
  </tbody>
</table>

Of course you can use different name for transposed DataFrame, or rename columns to include colon if it is mandatory.

EDIT: I missed the comma in the desired representation. If necessary, you can create new column for that

import pandas as pd
df=pd.DataFrame({'A': ['alfa 1', 'alfa 2'],
                 'B': ['beta 1', 'beta 2']})

df = df.transpose()
df['html'] = df.apply(lambda x:', '.join(x.astype(str)),1)
df.to_html('test.html', header=False, border=0, columns=['html'])

now the output is

<table border="0" class="dataframe">
  <tbody>
    <tr>
      <th>A</th>
      <td>alfa 1, alfa 2</td>
    </tr>
    <tr>
      <th>B</th>
      <td>beta 1, beta 2</td>
    </tr>
  </tbody>
</table>

Upvotes: 1

AKS
AKS

Reputation: 19811

df.to_dict('list') will return a dict with column name as key and the rows as a list of values.

>>> df.to_dict('list')
{'A': ['alfa 1', 'alfa 2'], 'B': ['beta 1', 'beta 2']}

From there, we can use dict comphrehension along with str.join to get the expected output:

>>> '<br>'.join(f"{key}: {', '.join(data)}" for key, data in df.to_dict('list').items())
'A: alfa 1, alfa 2<br>B: beta 1, beta 2'

Upvotes: 1

balderman
balderman

Reputation: 23815

The below works

import pandas as pd

df = pd.DataFrame({'A': ['alfa 1', 'alfa 2'],
                   'B': ['beta 1', 'beta 2']})

output = '<br>'.join([c + ' ' + ': '.join(r for r in df[c]) for c in df.columns])
print(output)

output

A alfa 1: alfa 2<br>B beta 1: beta 2

Upvotes: 1

Daweo
Daweo

Reputation: 36390

If you have

[['A: alfa 1', 'A: alfa 2'], ['B: beta 1', 'B: beta 2']]

you might use .join twice to get single str as follows

data = [['A: alfa 1', 'A: alfa 2'], ['B: beta 1', 'B: beta 2']]
data = [','.join(i) for i in data]
data = '<br>'.join(data)
print(data)

output

A: alfa 1,A: alfa 2<br>B: beta 1,B: beta 2

Upvotes: 1

Related Questions