Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace string with condition in pandas dataframe index

Tags:

python

pandas

I often use this kind of line which create or replace a column and assign a value according to a condition:

df.loc[df['somecolumn'].str.endswith('_s'), 'somecolumn'] = '_sp'

I would like to do the same thing, but for the index column. My specific question is how do I refer to the index column?

df.loc[df.index.str.endswith('_s'), 'index column name?'] = '_sp'

I tried using df.index.name, but it creates a new column instead of changing the values within the index column.

like image 330
OP40 Avatar asked Jan 26 '23 16:01

OP40


2 Answers

As i told in the comment section, You don't really need to use index.str.endswith until strictly it needs to be rather use anchors like for start ^ and endswith $ that should do a Job for you.

Just taking @Scott's sample for consideration.

df.index.str.replace(r'_s$', '_sp', regex=True)

I'm retaining this answer here for the sake of posterity ..

like image 122
Karn Kumar Avatar answered Jan 29 '23 05:01

Karn Kumar


IIUC,

import pandas as pd
import numpy as np
​
df = pd.DataFrame(np.random.randint(0,100,(5,5)), columns=['a_s','b','c_s','d','e'], index=['A','B_s','C','D_s','E_s'])
​
df.columns = df.columns.str.replace('_s','_sp')
df.index = df.index.str.replace('_s','_sp')
​
print(df)

Output:

      a_sp   b  c_sp   d   e
A       51  80    48  93  34
B_sp    96  16    73  15  29
C       27  85    35  93  69
D_sp    92  79    90  71  85
E_sp     4  63     2  77  14
like image 25
Scott Boston Avatar answered Jan 29 '23 07:01

Scott Boston