I have the following panda Series:
print(df.head())
Country Energy Supply Energy Supply per Capita % Renewable
0 Afghanistan 3.210000e+08 10 78.669280
1 Albania 1.020000e+08 35 100.000000
2 Algeria 1.959000e+09 51 0.551010
3 American Samoa NaN ... 0.641026
4 Andorra 9.000000e+06 121 88.695650
How can I rename Afghanistan to Afghanistan_new? I can set the index:
df = df.set_index('Country')
and then try to rename the country the following way:
df['Afghanistan'].rename('Afghanistan_renamed')
but it doesn't work.
Pandas DataFrame replace() MethodThe replace() method replaces the specified value with another specified value. The replace() method searches the entire DataFrame and replaces every case of the specified value.
You can replace values of all or selected columns based on the condition of pandas DataFrame by using DataFrame. loc[ ] property. The loc[] is used to access a group of rows and columns by label(s) or a boolean array. It can access and can also manipulate the values of pandas DataFrame.
replace() function is used to replace values in column (one value with another value on all columns). This method takes to_replace, value, inplace, limit, regex and method as parameters and returns a new DataFrame.
You can use the rename() method of pandas. DataFrame to change column/index name individually. Specify the original name and the new name in dict like {original name: new name} to columns / index parameter of rename() .
You can use if need replace index
:
df = df.set_index('Country')
df = df.rename(index={'Afghanistan':'Afghanistan_renamed'})
print (df)
Energy Supply Energy Supply per Capita % Renewable
Country
Afghanistan_renamed 3.210000e+08 10 78.669280
Albania 1.020000e+08 35 100.000000
Algeria 1.959000e+09 51 0.551010
American Samoa NaN ... 0.641026
Andorra 9.000000e+06 121 88.695650
and for replace
column:
df['Country'] = df['Country'].replace({'Afghanistan':'Afghanistan_renamed'})
df = df.set_index('Country')
print (df)
Energy Supply Energy Supply per Capita % Renewable
Country
Afghanistan_renamed 3.210000e+08 10 78.669280
Albania 1.020000e+08 35 100.000000
Algeria 1.959000e+09 51 0.551010
American Samoa NaN ... 0.641026
Andorra 9.000000e+06 121 88.695650
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With