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
.
Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss
Asked: 2022-11-25 11:00:00 +0000
Seen: 12 times
Last updated: Sep 27 '21
How to ensure a page break when creating Velocity HTML resumes?
What is the problem that arises when importing dynamic components in React with SSR?
What does an "Invalid Equation" error signify while creating HTML and MD reports using knitr?
In what way can I acquire the HTML source in C#?
Is it possible to have a HTML slider with two inputs?
How can HTML be integrated with Appjs React?
What is the reason behind getting the error message "File not found" in HTML?
What is the HTML tag for the title of the Divi Accordion module?
What is the process of incorporating "</>" into a HTML string?
What is the CSS that browsers use as default for HTML elements?