Reputation: 1765
please I have a python script that produces multiple dataframes: df1, df2, ..., df10. I would need ideally to export those dataframes all in one single pdf file but I realized that is quite complex. Hence, I'm trying to export the different dataframes into one single html file using the df.to_html() function. However, how can I export all my datafames into the same html file?
import numpy as np
from numpy.random import randn
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame(randn(5,4),columns='W X Y Z'.split())
df1 = pd.DataFrame(randn(5,4),columns='A B C D'.split())
df.head().to_html("testhtml.html")
df1.head().to_html("testhtml.html")
with the code above, the second .to_html instruction overrides the content of the first one, resulting with one single dataframe printed inside the html file. Is there any way to "append" the dataframes inside the same html file? Thank
Upvotes: 5
Views: 9184
Reputation: 3327
Use the .to_html()
to get the string and add them:
$ ipython
In [1]: import numpy as np
...: from numpy.random import randn
...: import pandas as pd
...: import matplotlib.pyplot as plt
...:
...: df = pd.DataFrame(randn(5,4),columns='W X Y Z'.split())
...: df1 = pd.DataFrame(randn(5,4),columns='A B C D'.split())
...:
In [2]: with open("a.html", 'w') as _file:
...: _file.write(df.head().to_html() + "\n\n" + df1.head().to_html())
...:
In [3]:
Do you really want to exit ([y]/n)? y
Now you will be able to see both the tables in the same file:
$ cat a.html
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>W</th>
<th>X</th>
<th>Y</th>
<th>Z</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>1.565874</td>
<td>1.612569</td>
<td>1.213773</td>
<td>-0.059322</td>
</tr>
<tr>
<th>1</th>
<td>-0.995417</td>
<td>-0.279548</td>
<td>0.204154</td>
<td>0.803098</td>
</tr>
<tr>
<th>2</th>
<td>-0.188367</td>
<td>-1.495322</td>
<td>0.675200</td>
<td>-2.432019</td>
</tr>
<tr>
<th>3</th>
<td>0.776902</td>
<td>2.642486</td>
<td>1.858429</td>
<td>0.024089</td>
</tr>
<tr>
<th>4</th>
<td>1.010742</td>
<td>0.065047</td>
<td>1.264571</td>
<td>-0.982195</td>
</tr>
</tbody>
</table>
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>A</th>
<th>B</th>
<th>C</th>
<th>D</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>-1.381432</td>
<td>-0.098652</td>
<td>-1.002030</td>
<td>0.133971</td>
</tr>
<tr>
<th>1</th>
<td>0.284307</td>
<td>0.566509</td>
<td>-0.640148</td>
<td>-0.284037</td>
</tr>
<tr>
<th>2</th>
<td>0.412460</td>
<td>-1.326584</td>
<td>-0.297338</td>
<td>0.531000</td>
</tr>
<tr>
<th>3</th>
<td>-0.456548</td>
<td>-0.354438</td>
<td>-0.675962</td>
<td>0.507228</td>
</tr>
<tr>
<th>4</th>
<td>-0.393275</td>
<td>0.462753</td>
<td>2.198363</td>
<td>-0.042263</td>
</tr>
</tbody>
Upvotes: 6