Abe
Abe

Reputation: 23918

python pandas: Rename a series within a dataframe?

I'm using python pandas for data analysis and I want to change the name of a series in a dataframe.

This works, but it seems very inefficient:

AA = pandas.DataFrame( A )
for series in A:
    AA[A_prefix+series] = A[series]
    del A[series]

Is there a way to change the series name in place?

Upvotes: 1

Views: 4683

Answers (1)

DSM
DSM

Reputation: 353099

Sure, you can use the rename method:

In [11]: df = DataFrame({"A": [1,2], "B": [3,4]})

In [12]: df.rename(columns={"A": "series formerly known as A"})
Out[12]: 
   series formerly known as A  B
0                           1  3
1                           2  4

This doesn't change df, though:

In [13]: df
Out[13]: 
   A  B
0  1  3
1  2  4

You can get that behaviour if you want using inplace:

In [14]: df.rename(columns={"A": "series formerly known as A"}, inplace=True)
Out[14]: 
   series formerly known as A  B
0                           1  3
1                           2  4

In [15]: df
Out[15]: 
   series formerly known as A  B
0                           1  3
1                           2  4

Upvotes: 8

Related Questions