Python 如何忽略列表中的NaN值?

Python 如何忽略列表中的NaN值?,python,excel,pandas,list,nan,Python,Excel,Pandas,List,Nan,我有一个Excel文件,其中有一列包含测量值,例如: 测量值 24235 325434 此值为空,因此为NaN值 # init the counter counter = 0 # iterate on the list and pick list element one by one for each in f: try: # .. doWork() ... counter += int(each) # convert the element t

我有一个Excel文件,其中有一列包含测量值,例如:

测量值

24235

325434

此值为空,因此为NaN值

# init the counter
counter = 0    
# iterate on the list and pick list element one by one
for each in f:         
  try:
    # .. doWork() ... 
    counter += int(each)  # convert the element to int. if something wrong we will get ValueError which we will catch/except later.
  except ValueError:      # if we get valueerror exception that   means we hit nan. so we skip and continue. 
    pass   # you can use continue instead of using pass, both are valid!
45345

我正在将该列从excel提取到一个python列表中,结果是:list=['24235','325434','nan','45435']。我想忽略NaN值,以便能够计算总测量值。我这样做是为了避免考虑NaN值,但它不起作用:

if list[i] != 'nan' or list[i] != float('NaN'):
    counter += int(list[i])

它正在输入if语句,即使它是假的。我怎样才能解决这个问题

尝试,ValueError除外

使用try-except并防止使用if..else旧式风格。这样做效率更高,可以避免编写冗长复杂的逻辑。请注意我的评论内联

# init the counter
counter = 0    
# iterate on the list and pick list element one by one
for each in f:         
  try:
    # .. doWork() ... 
    counter += int(each)  # convert the element to int. if something wrong we will get ValueError which we will catch/except later.
  except ValueError:      # if we get valueerror exception that   means we hit nan. so we skip and continue. 
    pass   # you can use continue instead of using pass, both are valid!
我们只想排除
ValueError
异常,因为它是由无效的
int()
转换引起的,比如
int(nan)

对于彼此的例外,我们想提出它

您可以像这样过滤掉“nan”元素:

original = ['24235', '325434', 'nan', '45435']
filtered = [int(element) for element in original if element != 'nan']
print(sum(filtered))
输出:

395104

不知道这在纯python中是否有效,但在pandas的NAN中有效:试着对照自身检查值:
if list[i]==list[i]:counter+=int(list[i])
这不总是正确的吗@但事实并非如此,至少在熊猫的南部。我曾经读过对这种现象的解释,据说NaN是以一种特定的方式建立的,他们不等于他们自己。由于您使用的是纯python,我不知道您使用的NaN是否与pandasOh的NaN的行为相同,好吗。我本以为NaN等于NaN,但我猜不是。我感谢你的帮助,非常感谢@Olenscki很好。。。当我第一次听到它的时候,我也感到很困惑,但它也对我当时的问题起到了作用!我认为
continue
应该改为
pass
,而
try except
块应该在循环中。另外,
计数器
需要先初始化。你说得对,我错了。我会修好的。为什么不在循环内尝试呢?。除了在循环内,无需进入try。我可以输入它,但它是一样的,如果在转换过程中出现了一些错误,那么异常将继续告诉hiting第一个
try
好吧,您希望代码忽略ValueErrors,并且列表中可能有许多“nan”。如果块在循环外,执行将在第一个“nan”处停止。哦,伙计,我需要咖啡。非常感谢。我会修好的:-)我是tired@PApostol-关于
pass
continue
在我发布修复后都有效。我没有尝试此解决方案,但我感谢您的时间和努力。非常感谢。