I have a dataframe:
df = pd.DataFrame({"by_week": list_1, "by_month": list_2})
Now I need to get a html table html = df.to_html()
where columns are generated like:
<tr>
<th></th>
<th>by_month</th>
<th>by_week</th>
</tr>
But I'm looking for more human-readable header column like:
<tr>
<th></th>
<th>Last 7 days</th>
<th>Last 30 days</th>
</tr>
I have two options for solving it: Option 1
html = html.replace("by_week", "Last 7 days").replace("by_month", "Last 30 days")
But code is messy
Option 2
df = pd.DataFrame({"Last 7 days": list_1, "Last 30 days": list_2})
but it is hard to write/access to a specific column each time.
so... Does alias for columns exist?
One way of renaming the columns in a Pandas Dataframe is by using the rename() function.
Pandas has a built-in function called rename() to change the column names. It's useful when you want to rename some selected columns.
Aliases for columns names are not supported yet.
I think you can rename columns by dict
:
list_1 = [1,2]
list_2 = [5,7]
d = {"by_week": "Last 7 days", "by_month": "Last 30 days"}
df = pd.DataFrame({"by_week": list_1, "by_month": list_2}).rename(columns=d)
print (df)
Last 30 days Last 7 days
0 5 1
1 7 2
df = pd.DataFrame({"by_week": list_1, "by_month": list_2}).rename(columns=d).to_html()
print (df)
<table border="1" class="dataframe">
<thead>
<tr style="text-align: right;">
<th></th>
<th>Last 30 days</th>
<th>Last 7 days</th>
</tr>
</thead>
<tbody>
<tr>
<th>0</th>
<td>5</td>
<td>1</td>
</tr>
<tr>
<th>1</th>
<td>7</td>
<td>2</td>
</tr>
</tbody>
</table>
Use rename
df.rename(columns={"by_week": "Last 7 days", "by_month": "Last 30 days"}).to_html()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With