重命名 Pandas DataFrame 索引 [英] Rename Pandas DataFrame Index

查看:77
本文介绍了重命名 Pandas DataFrame 索引的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个没有标题的 csv 文件,带有日期时间索引.我想重命名索引和列名,但使用 df.rename() 只重命名列名.漏洞?我使用的是 0.12.0 版

I've a csv file without header, with a DateTime index. I want to rename the index and column name, but with df.rename() only the column name is renamed. Bug? I'm on version 0.12.0

In [2]: df = pd.read_csv(r'D:DataDataTimeSeries_csv//seriesSM.csv', header=None, parse_dates=[[0]], index_col=[0] )

In [3]: df.head()
Out[3]: 
                   1
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

In [4]: df.rename(index={0:'Date'}, columns={1:'SM'}, inplace=True)

In [5]: df.head()
Out[5]: 
                  SM
0                   
2002-06-18  0.112000
2002-06-22  0.190333
2002-06-26  0.134000
2002-06-30  0.093000
2002-07-04  0.098667

推荐答案

rename 方法采用字典作为索引,该索引适用于索引 values.
您想重命名为索引级别的名称:

The rename method takes a dictionary for the index which applies to index values.
You want to rename to index level's name:

df.index.names = ['Date']

考虑这一点的一个好方法是列和索引是同一类型的对象(IndexMultiIndex),您可以将两者互换通过转置.

A good way to think about this is that columns and index are the same type of object (Index or MultiIndex), and you can interchange the two via transpose.

这有点令人困惑,因为索引名称与列的含义相似,因此这里有更多示例:

This is a little bit confusing since the index names have a similar meaning to columns, so here are some more examples:

In [1]: df = pd.DataFrame([[1, 2, 3], [4, 5 ,6]], columns=list('ABC'))

In [2]: df
Out[2]: 
   A  B  C
0  1  2  3
1  4  5  6

In [3]: df1 = df.set_index('A')

In [4]: df1
Out[4]: 
   B  C
A      
1  2  3
4  5  6

可以在索引上看到重命名,可以改变 1:

You can see the rename on the index, which can change the value 1:

In [5]: df1.rename(index={1: 'a'})
Out[5]: 
   B  C
A      
a  2  3
4  5  6

In [6]: df1.rename(columns={'B': 'BB'})
Out[6]: 
   BB  C
A       
1   2  3
4   5  6

重命名关卡名称时:

In [7]: df1.index.names = ['index']
        df1.columns.names = ['column']

注意:此属性只是一个列表,您可以将重命名为列表理解/映射.

Note: this attribute is just a list, and you could do the renaming as a list comprehension/map.

In [8]: df1
Out[8]: 
column  B  C
index       
1       2  3
4       5  6

这篇关于重命名 Pandas DataFrame 索引的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆