Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alias for column in pandas

Tags:

python

pandas

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?

like image 208
Cristhian Boujon Avatar asked Sep 07 '17 12:09

Cristhian Boujon


People also ask

How do I name a column name in pandas?

One way of renaming the columns in a Pandas Dataframe is by using the rename() function.

How do I rename a column name in pandas CSV?

Pandas has a built-in function called rename() to change the column names. It's useful when you want to rename some selected columns.


2 Answers

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>
like image 96
jezrael Avatar answered Sep 18 '22 13:09

jezrael


Use rename

df.rename(columns={"by_week": "Last 7 days", "by_month": "Last 30 days"}).to_html()

like image 33
Zero Avatar answered Sep 18 '22 13:09

Zero