感谢您提供的任何帮助。如果还有与此问题相关的其他帖子/视频/文章,我很乐意查看。
语言:Python
我的问题:构造下面的代码以跳过列表= num中的“ N / A”和“ Dec 25 2019”的正确方法是什么?
我找到了如何将“ 1.19T”之类的字母数字值转换为浮点数的答案,但是我不知道如何跳过日期和列表中的“ N / A”。任何帮助,将不胜感激,谢谢。
num = ["11.1", "1.19T", "22.14", "2.09B", "4.57%", "12.92", "N/A", "Dec 25 2019"]
units = {"M": 1_000, "B": 1_000_000, "T": 1_000_000_000, "": 1, "%": .01}
result = []
for n in num:
try:
result.append(float(n))
except ValueError:
unit = n[-1]
n = float(n[:-1])
result.append(n * units[unit])
print(result)
for n in num:
try:
if n[-1] in units:
n = float(n[:-1]) * units[n[-1]]
else:
n = float(n)
except ValueError:
continue
result.append(n)
如注释中所建议,另一种方法是使用嵌套的try / except块。但是,“显式优于隐式”,所以我更喜欢上面的一种。
units
中删除空字符串键:units = {"M": 1_000, "B": 1_000_000, "T": 1_000_000_000, "%": .01}
然后我遍历所有元素和所有保存的单元,以将所有文字修改为正确的算术运算:
>>> num_formatted=[]
>>> for el in num:
... x=el
... for k in units:
... x=re.sub(r"([0-9\.]+)"+k, r"(\1 * "+str(units[k])+")", x)
... num_formatted.append(x)
...
>>> print(num_formatted)
['11.1', '(1.19 * 1000000000)', '22.14', '(2.09 * 1000000)', '(4.57 * 0.01)', '12.92', 'N/A', 'Dec 25 2019']
然后eval
以上所有对象:
>>> import numpy as np
>>> num_formatted_final=[]
>>> for el in num_formatted:
... try:
... num_formatted_final.append(eval(el))
... except:
... num_formatted_final.append(np.nan)
...
>>> num_formatted_final
[11.1, 1190000000.0, 22.14, 2089999.9999999998, 0.045700000000000005, 12.92, nan, nan]