How to rename a series of pandas?

How can I change the name of a Series object?

+7
source share
5 answers

You can do this by changing the name attribute of your subs object:

Assuming its name is 'Settle' and you want to change it, say, 'Unsettle' , simply update the name attribute, for example, like this:

 In [16]: s = Series(randn(10), name='Settle') In [17]: s Out[17]: 0 0.434 1 -0.581 2 -0.263 3 -1.384 4 -0.075 5 -0.956 6 0.166 7 0.138 8 -0.770 9 -2.146 Name: Settle, dtype: float64 In [18]: s.name Out[18]: 'Settle' In [19]: s.name = 'Unsettle' In [20]: s Out[20]: 0 0.434 1 -0.581 2 -0.263 3 -1.384 4 -0.075 5 -0.956 6 0.166 7 0.138 8 -0.770 9 -2.146 Name: Unsettle, dtype: float64 In [21]: s.name Out[21]: 'Unsettle' 
+24
source
 s.reset_index(name="New_Name") 

or

 s.to_frame("New_Name")["New_Name"] 
+4
source

Series.rename , I have not seen this, but you can use Series.rename if you do not want to modify the existing series.

 s = pd.Series('x', index=range(5), name='myseries') s 0 x 1 x 2 x 3 x 4 x Name: myseries , dtype: object t = s.rename('foobar') t 0 x 1 x 2 x 3 x 4 x Name: foobar , dtype: object s.name # 'myseries' t.name # 'foobar' 

But why work with a function?
Chain method. It’s just more convenient to do

 ser.method1().rename('foobar').method2().method3() 

Vs

 ser = ser.method1() ser.name = 'foobar' ser.method2().method3() 

With rename you can create a smooth chain of function calls.

+2
source

Finally, I renamed my Series object to Desired_Name as follows

 # Let my_object be the pandas.Series object my_object.name = 'Desired_Name' 

Then the automatically generated name, which is now read in the legend, is now called "Desired_Name" instead of "Settle" earlier.

0
source

Not sure why no one mentioned renaming

 s.rename("new_name", inplace=True) 
0
source

Source: https://habr.com/ru/post/1499968/


All Articles