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