1 | initial version |
To combine two columns from a DataFrame into a single column in an HTML table, we can use the pandas method apply()
and a lambda function to concatenate the values of the two columns. Here's an example code:
import pandas as pd
# create a sample DataFrame
df = pd.DataFrame({'col1': ['a', 'b', 'c'], 'col2': ['d', 'e', 'f']})
# create a new column by concatenating the values of col1 and col2
df['new_col'] = df.apply(lambda row: row['col1'] + '-' + row['col2'], axis=1)
# create an HTML table
html_table = df.to_html()
# print the HTML table
print(html_table)
Output:
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>col1</th>
<th>col2</th>
<th>new_col</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>a</td>
<td>d</td>
<td>a-d</td>
</tr>
<tr>
<th>1</th>
<td>b</td>
<td>e</td>
<td>b-e</td>
</tr>
<tr>
<th>2</th>
<td>c</td>
<td>f</td>
<td>c-f</td>
</tr>
</tbody>
</table>
In the example above, we create a new column called new_col
by concatenating the values of col1
and col2
using a lambda function. Then, we use the to_html()
method to convert the DataFrame into an HTML table. The resulting HTML table has three columns (col1
, col2
, and new_col
), where new_col
combines the values of col1
and col2
.