Pandas 中列的别名
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46096307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Alias for column in pandas
提问by Cristhian Boujon
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:
现在我需要得到一个 html 表html = df.to_html()
,其中生成的列如下:
<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
我有两种解决方法: 选项 1
html = html.replace("by_week", "Last 7 days").replace("by_month", "Last 30 days")
But code is messy
但是代码很乱
Option 2
选项 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?
所以...列的别名是否存在?
回答by jezrael
Aliases for columns names are not supported yet.
尚不支持列名称的别名。
I think you can rename columns by dict
:
我认为您可以通过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>
回答by Zero
Use rename
用 rename
df.rename(columns={"by_week": "Last 7 days", "by_month": "Last 30 days"}).to_html()
df.rename(columns={"by_week": "Last 7 days", "by_month": "Last 30 days"}).to_html()