重新命名 pandas DataFrame索引 [英] Rename Pandas DataFrame Index
问题描述
在[2]中:df = pd.read_csv(r'D:\Data \DataTimeSeries_csv // seriesSM.csv',header = None,parse_dates = [[0]],index_col = [0])
在[3]中:df.head()
出[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
在[4]中:df.rename(index = {0:'Date'},columns = {1:'SM' },inplace = True
在[5]中:df.head()
输出[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
重命名
您要重命名为索引级别的名称:
df.index.names = ['Date' ]
想想这个的好方法是列和索引是相同类型的对象(索引
或 MultiIndex
),您可以通过转置来交换两个。
这是一个有点混乱,因为索引名称具有与列相似的含义,所以这里有更多的例子:
在[1]中:df = pd.DataFrame([[1,2,3],[4,5,6]],columns = list('ABC')
在[2]中:df
输出[2]:
ABC
0 1 2 3
1 4 5 6
[3]:df1 = df.set_index('A')
在[4]中:df1
输出[4]:
BC
A
1 2 3
4 5 6
您可以在索引上看到重命名,可以更改值 1:
在[5]中:df1.rename(index = {1 :'a'})
出[5]:
BC
A
a 2 3
4 5 6
在[6] :df1.rename(columns = {'B':'BB'})
输出[6]:
BB C
A
1 2 3
4 5 6
在重命名级别名称时:
在[7]中:df1.index.names = ['index']
df1.columns.names = ['column']
注意:此属性只是列表,您可以将其重命名为列表理解/映射。
在[8]中:df1
[8]:
列BC
索引
1 2 3
4 5 6
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:\Data\DataTimeSeries_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
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']
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
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
Whilst renaming the level names:
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屋!