One - One Code All

Blog Content

pandas中DateFrame修改列名rename

Python 统计学-科学计算   2014-04-03 22:32:16

Pandas中DateFrame修改列名

在做数据挖掘的时候,想改一个DataFrame的column名称,所以就查了一下,总结如下: 


数据如下:


>>>import pandas as pd

>>>a = pd.DataFrame({'A':[1,2,3], 'B':[4,5,6], 'C':[7,8,9]})

>>> a 

   A  B  C

0  1  4  7

1  2  5  8

2  3  6  9


方法一:暴力方法

>>>a.columns = ['a','b','c']

>>>a

   a  b  c

0  1  4  7

1  2  5  8

2  3  6  9


但是缺点是必须写三个,要不报错。


方法二:较好的方法

>>>a.rename(columns={'A':'a', 'B':'b', 'C':'c'}, inplace = True)

>>>a

   a  b  c

0  1  4  7

1  2  5  8

2  3  6  9


好处是可以随意改个数:


>>>a.rename(columns={'A':'a', 'C':'c'}, inplace = True)

>>>a

   a  B  c

0  1  4  7

1  2  5  8

2  3  6  9


可以只改变’A’,’C’,不改变’B’。



上一篇:python虚拟环境--virtualenv
下一篇:pandas之排序函数sort_values("col")

The minute you think of giving up, think of the reason why you held on so long.