Alias for Column in Pandas

Alias for Column in 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?

3 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>

Use rename

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

As I already suggested here another possible solution to effectively mimic aliasing columns without actually aliasing them is this:

Just define some constants and then use those to access your columns in your code:

class Columns:
    colA = "My tediously long name for column A"
    colB = "Yet another long column name"
    colC = "Some column with $\emph{special}$ symbols in it"

df = pd.read_csv(...)

print(df[Columns.colA])

Using a separate class to create a namespace for the column constants is of course optional and you can omit it if you prefer.

If I did not miss anything, this seems to fit all scenarios in which one would want to use aliases, unless you are trying to alias some columns to allow something like column-duck-typing. But I guess that would probably only get messy really quickly anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Alexander Ross
Author

Alexander Ross

Alexander Ross has covered the video game industry for a decade, writing deep dives on game design, esports tournaments, VR developments, and gaming culture.