Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I change a single index value in pandas dataframe?

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?

like image 553
user517696 Avatar asked Nov 04 '16 16:11

user517696


People also ask

How do you replace a single value in a DataFrame?

(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',...])

How do you reassign an index in Python?

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() .

How do I change an index in a DataFrame?

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.

How do I change a specific index in pandas?

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.


1 Answers

@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 
like image 192
ErnestScribbler Avatar answered Sep 20 '22 03:09

ErnestScribbler