简体   繁体   English

将系列中的 str 值替换为 np.nan

[英]Replace str values in series into np.nan

I have the following series我有以下系列

s = pd.Series({'A':['hey','hey',2,2.14},index=1,2,3,4)

I basically want to mask, the series and check if the values are a str if so i want to replace then with np.nan, how could i achieve that?我基本上想屏蔽系列并检查值是否是 str,如果我想用 np.nan 替换,我怎么能实现呢?

Wanted result想要的结果

s = pd.Series({'A':[np.nan,np.nan,2,2.14},index=1,2,3,4)

I tried this我试过这个

s.mask(isinstance(s,str))

But i got the following ValueError: Array conditional must be same shape as self, i am kinda a newb when it comes to these methods would appreciate a explanation on the why但我得到了以下 ValueError:条件数组必须与自身形状相同,当涉及到这些方法时,我有点新手希望能解释为什么

You can use您可以使用

out = s.mask(s.apply(type).eq(str))
print(out)

1     NaN
2     NaN
3       2
4    2.14
dtype: object

Use to_numeric with the errors="coerce" parameter.to_numericerrors="coerce"参数一起使用。

s = pd.to_numeric(s, errors = 'coerce')
Out[73]: 
1     NaN
2     NaN
3    2.00
4    2.14
dtype: float64

If you are set on using mask , you could try:如果您打算使用mask ,您可以尝试:

s = pd.Series(['hey','hey',2,2.14],index=[1,2,3,4])
s.mask(s.apply(isinstance,args = [str]))
print(s)

1     NaN
2     NaN
3       2
4    2.14
dtype: object

But as you can see, many roads leading to Rome...但如你所见,条条大路通罗马……

IIUC, You need to createpd.Series like below then use isinstance like below. IIUC,您需要像下面这样创建pd.Series ,然后像下面这样使用isinstance

import numpy as np
import pandas as pd
s = pd.Series(['hey','hey',2,2.14],index=[1,2,3,4])
s = s.apply(lambda x: np.nan if isinstance(x, str) else x)
print(s)

1     NaN
2     NaN
3    2.00
4    2.14
dtype: float64

You could use:你可以使用:

s[s.str.match('\D+').fillna(False)] = np.nan

But if you are looking to convert all string 'types' not just representations like "1.23" then refer to @Ynjxsjmh's answer.但是,如果您希望转换所有字符串“类型”而不仅仅是像“1.23”这样的表示,那么请参考@Ynjxsjmh 的回答。

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

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