energy.loc['Republic of Korea']
I want to change the value of index from 'Republic of Korea' to 'South Korea'. But the dataframe is too large and it is not possible to change every index value. How do I change only this single value?
(3) Replace multiple values with multiple new values for an individual DataFrame column: df['column name'] = df['column name']. replace(['1st old value','2nd old value',...],['1st new value','2nd new value',...])
If you want to keep the original index as a column, use reset_index() to reassign the index to a sequential number starting from 0 . You can change the index to a different column by using set_index() after reset_index() .
DataFrame - set_index() function The set_index() function is used to set the DataFrame index using existing columns. Set the DataFrame index (row labels) using one or more existing columns or arrays of the correct length. The index can replace the existing index or expand on it.
To change the index values we need to use the set_index method which is available in pandas allows specifying the indexes. where, inplace parameter accepts True or False, which specifies that change in index is permanent or temporary. True indicates that change is Permanent.
@EdChum's solution looks good. Here's one using rename, which would replace all these values in the index.
energy.rename(index={'Republic of Korea':'South Korea'},inplace=True)
Here's an example
>>> example = pd.DataFrame({'key1' : ['a','a','a','b','a','b'], 'data1' : [1,2,2,3,nan,4], 'data2' : list('abcdef')}) >>> example.set_index('key1',inplace=True) >>> example data1 data2 key1 a 1.0 a a 2.0 b a 2.0 c b 3.0 d a NaN e b 4.0 f >>> example.rename(index={'a':'c'}) # can also use inplace=True data1 data2 key1 c 1.0 a c 2.0 b c 2.0 c b 3.0 d c NaN e b 4.0 f
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