Ask Your Question
2

How can we combine two columns from a dataframe into a single column in an HTML table?

asked 2022-11-25 11:00:00 +0000

pufferfish gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
2

answered 2021-09-27 19:00:00 +0000

david gravatar image

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.

edit flag offensive delete link more

Your Answer

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

Add Answer


Question Tools

Stats

Asked: 2022-11-25 11:00:00 +0000

Seen: 12 times

Last updated: Sep 27 '21