我有一个没有标题的csv文件,带有日期时间索引.我想重命名索引和列名,但要使用df.rename()只重命名列名.缺陷我的版本是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

推荐答案

rename方法获取适用于索引values的索引的字典.
您想要重命名为索引级的名称:

df.index.names = ['Date']

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

这有点让人困惑,因为索引名与列的含义相似,所以这里有更多的例子:

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

您可以在索引上看到重命名,它可以更改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']

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

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

Python相关问答推荐

日程优化问题不知道更好的方式来呈现解决方案- Python / Gekko

如何从. text中进行pip安装跳过无法访问的库

使用Python从HTTP打印值

使用argsorted索引子集索引数组

在Python中管理多个OpenGVBO和VAO实例

Python会扔掉未使用的表情吗?

SQLGory-file包FilField不允许提供自定义文件名,自动将文件保存为未命名

try 在树叶 map 上应用覆盖磁贴

未删除映射表的行

如何让Flask 中的请求标签发挥作用

用Python解密Java加密文件

Python中绕y轴曲线的旋转

SQLAlchemy Like ALL ORM analog

在pandas中使用group_by,但有条件

如何在UserSerializer中添加显式字段?

在单个对象中解析多个Python数据帧

实现神经网络代码时的TypeError

如何在Python中获取`Genericums`超级类型?

为什么\b在这个正则表达式中不解释为反斜杠

寻找Regex模式返回与我当前函数类似的结果