Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to replace a part of a string in a pandas.Dataframe?

I am trying to replace a part of all strings in pd.Dataframe, but it doe s not work.

My data example:

HLAA0101    
HLAA0201    
HLAA0202    
HLAA0203    
HLAA0205 

What am I trying to obtain:

A0101    
A0201    
A0202    
A0203    
A0205 

My code:

 mhc = train_csv.mhc

 for i in mhc:
   i[0:2].replace('HLA', ' ')

 print(mhc)

But it does not work.

like image 442
danya tekunov Avatar asked Nov 20 '25 15:11

danya tekunov


2 Answers

Option 1:

df['mhc'] = df['mhc'].str[3:]

Option 2:

df['mhc'] = df['mhc'].str.replace(r'^HLA','')

Option 3:

df['mhc'] = df['mhc'].str.extract(r'HLA(.*)', expand=False)

Option 4: (NOTE: sometimes list comprehension works faster than internal vectorized methods for string/object dtypes)

df['mhc'] = [s[3:] for s in df['mhc']]

All options yield the same result:

In [26]: df
Out[26]:
     mhc
0  A0101
1  A0201
2  A0202
3  A0203
4  A0205

Timing for 50.000 rows DF:

In [29]: df = pd.concat([df] * 10**4, ignore_index=True)

In [30]: %timeit df['mhc'].str[3:]
35.9 ms ± 3.18 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [31]: %timeit df['mhc'].str.replace(r'^HLA','')
162 ms ± 3.04 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [32]: %timeit df['mhc'].str.extract(r'HLA(.*)', expand=False)
164 ms ± 4.87 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

In [33]: %timeit [s[3:] for s in df['mhc']]
14.6 ms ± 18.6 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)

In [34]: df.shape
Out[34]: (50000, 1)

Conclusion: list comprehension approach won.

like image 103
MaxU - stop WAR against UA Avatar answered Nov 22 '25 06:11

MaxU - stop WAR against UA


Use -

mhc = mhc.str.replace('HLA', ' ')

OR -

train_csv['mhc'] = train_csv['mhc'].str.replace('HLA', '') # One liner directly from df
like image 22
Vivek Kalyanarangan Avatar answered Nov 22 '25 04:11

Vivek Kalyanarangan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!