如何在pandas.Dataframe中替换字符串的一部分?

我试图替换pd.Dataframe中所有字符串的一部分,但它不起作用.

我的数据示例:

HLAA0101    
HLAA0201    
HLAA0202    
HLAA0203    
HLAA0205 

我想要获得什么:

A0101    
A0201    
A0202    
A0203    
A0205 

我的代码:

 mhc = train_csv.mhc

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

 print(mhc)

但它不起作用.

最佳答案 选项1:

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

选项2:

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

选项3:

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

选项4 :(注意:有时列表理解比字符串/对象dtypes的内部向量化方法更快)

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

所有选项都会产生相同的结果:

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

时间为50.000行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)

结论:列表理解方法获胜.

点赞