简体   繁体   English

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

[英]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. 我试图替换pd.Dataframe中所有字符串的一部分,但它不起作用。

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. 但它不起作用。

Option 1: 选项1:

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

Option 2: 选项2:

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

Option 3: 选项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) 选项4 :(注意:有时列表理解比字符串/对象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: 时间为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)

Conclusion: list comprehension approach won. 结论:列表理解方法获胜。

Use - 使用 -

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

OR - 要么 -

train_csv['mhc'] = train_csv['mhc'].str.replace('HLA', '') # One liner directly from df

Try str.replace . 试试str.replace (Documentation here: https://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html ) (此处的文档: https//pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.str.replace.html

Also, in your code it inserts a space instead of the replaced strings. 此外,在您的代码中,它插入一个空格而不是替换的字符串。 If you want that, that's fine, otherwise delete the space. 如果你想要,那很好,否则删除空格。 ;) ;)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM