提取引号内的对象类型
Extract type of object inside quotation marks
我有以下列表:
l = ['AB', '27.0', '30.5', '28', '31', 'CD', '29']
我想把每个数值变成float
,每个string
变成np.nan
。
到目前为止,我的尝试失败了,因为 float('AB')
显然无法计算:
result = [float(i) if isinstance(float(i), float) else np.nan for i in l]
期望的结果是:
result = [np.nan, 27.0, 30.5, 28.0, 31.0, np.nan, 29.0]
你建议我应该做什么?
改用re.search
:
result = [float(i) if re.search(r'^\d+(?:\.\d+)?$', i) else np.nan for i in l]
使用"It's easier to ask for forgiveness than permission" principle的Python理想:
EAFP:
Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
这避免了额外的开销,例如正则表达式搜索,并在您的输入中使用浮点数和整数:
def to_float(value: str):
try:
return float(value)
except ValueError:
return np.nan
result = [to_float(value) for value in l]
如果数字是您示例中的整数:
result = [ float(i) if i.isdigit() else np.nan for i in l ]
如果我没理解错的话,您只需要确定一个字符串是否为数字即可。如果它的数字我们更改为 float 否则我们给它 np.nan
所以我们可以这样解决问题:
y = []
for x in l:
if x.isnumeric():
x = float(x)
y.append(x)
else:
x=np.nan
y.append(x)
编辑:
我们还可以通过反向方式来解决这个问题,我们检查字符串是否是字母表
所以代码可以是这样的:
z = []
for x in l:
if x.isalpha():
x = np.nan
z.append(x)
else:
x = float(x)
z.append(x)
print(z)
我得到的结果是:
[nan, 27.0, 30.5, 28.0, 31.0, nan, 29.0]
希望对您有所帮助
我有以下列表:
l = ['AB', '27.0', '30.5', '28', '31', 'CD', '29']
我想把每个数值变成float
,每个string
变成np.nan
。
到目前为止,我的尝试失败了,因为 float('AB')
显然无法计算:
result = [float(i) if isinstance(float(i), float) else np.nan for i in l]
期望的结果是:
result = [np.nan, 27.0, 30.5, 28.0, 31.0, np.nan, 29.0]
你建议我应该做什么?
改用re.search
:
result = [float(i) if re.search(r'^\d+(?:\.\d+)?$', i) else np.nan for i in l]
使用"It's easier to ask for forgiveness than permission" principle的Python理想:
EAFP: Easier to ask for forgiveness than permission. This common Python coding style assumes the existence of valid keys or attributes and catches exceptions if the assumption proves false. This clean and fast style is characterized by the presence of many try and except statements. The technique contrasts with the LBYL style common to many other languages such as C.
这避免了额外的开销,例如正则表达式搜索,并在您的输入中使用浮点数和整数:
def to_float(value: str):
try:
return float(value)
except ValueError:
return np.nan
result = [to_float(value) for value in l]
如果数字是您示例中的整数:
result = [ float(i) if i.isdigit() else np.nan for i in l ]
如果我没理解错的话,您只需要确定一个字符串是否为数字即可。如果它的数字我们更改为 float 否则我们给它 np.nan
所以我们可以这样解决问题:
y = []
for x in l:
if x.isnumeric():
x = float(x)
y.append(x)
else:
x=np.nan
y.append(x)
编辑:
我们还可以通过反向方式来解决这个问题,我们检查字符串是否是字母表 所以代码可以是这样的:
z = []
for x in l:
if x.isalpha():
x = np.nan
z.append(x)
else:
x = float(x)
z.append(x)
print(z)
我得到的结果是:
[nan, 27.0, 30.5, 28.0, 31.0, nan, 29.0]
希望对您有所帮助