熊猫Series.tolist()中的NaN与列表中的NaN行为不同 - python

为什么

>> import pandas as pd
>> import numpy as np

>> list(pd.Series([np.nan, np.nan, 2, np.nan, 2])) == [np.nan, np.nan, 2, np.nan, 2]

返回False?用pd.Series([np.nan, np.nan, 2, np.nan, 2]).tolist()得到相同的结果。我试图通过以下函数计算pandas groupby对象(因此基本上是pandas系列)中最常见的元素

def get_most_common(srs):
    """
    Returns the most common value in a list. For ties, it returns whatever
    value collections.Counter.most_common(1) gives.
    """
    from collections import Counter

    x = list(srs)
    my_counter = Counter(x)
    most_common_value = my_counter.most_common(1)[0][0]

    return most_common_value

并意识到即使我有x = list(srs)步骤,我对多个NaN的计数也有误。

编辑:
只是为了阐明为什么这对我来说是一个问题:

>>> from collections import Counter
>>> Counter(pd.Series([np.nan, np.nan, np.nan, 2, 2, 1, 5]).tolist())
Counter({nan: 1, nan: 1, nan: 1, 2.0: 2, 1.0: 1, 5.0: 1}) # each nan is counted differently
>>> Counter([np.nan, np.nan, np.nan, 2, 2, 1, 5])
Counter({nan: 3, 2: 2, 1: 1, 5: 1}) # nan count of 3 is correct

python大神给出的解决方案

正如@emilaz已经指出的,根本问题是在所有情况下都是nan != nan。但是,在您的观察中,重要的是对象引用。

观察listpd.Series之间的以下对象引用:

>>> s = pd.Series([np.nan, np.nan, np.nan, 2, 2, 1, 5])
>>> s.apply(id)
0    149706480
1    202463472
2    202462336
3    149706912
4    149706288
5    149708784
6    149707200
dtype: int64

>>> l = [np.nan, np.nan, np.nan, 2, 2, 1, 5]
>>> list(map(id, l))
[68634768, 68634768, 68634768, 1389126848, 1389126848, 1389126832, 1389126896]

np.nan对象与np.nan中导入的list对象共享相同的引用,而为每个Series创建一个新引用(对于pandas用法很有意义)。

因此,答案不是以这种方式比较nanpandas有其自己的方式来处理nan,因此根据您的实际活动,答案可能会比您想像的要简单得多(例如df.groupby('some col').count())。

Python-熊猫描述了抛出错误:无法散列的类型“ dict” - python

更新:我正在使用“ Socrata开源API”中的一些示例代码。我在代码中注意到以下注释:# First 2000 results, returned as JSON from API / converted to Python # list of dictionaries by sodapy. 我不熟悉JSON。我已经下载了一个数据集,并创建了一个包含大量…

子条件的python条件覆盖 - python

我试图找到一个python代码覆盖率工具,该工具可以衡量语句中是否包含子表达式:例如,我想看看下面的示例是否涵盖了condition1 / condition2 / condtion3?if condition1 or condition2 or condition3: x = true_value python大神给出的解决方案 对此的唯一合理答案是:当前…

USB设备发行 - python

我目前正在使用PyUSB。由于我不熟悉USB,所以我不知道如何执行以下操作。我已经从Python PyUSB成功连接到我的USB设备硬件。在代码中,我需要重置USB设备硬件。通过向硬件发送命令来完成。现在,在硬件重置后,我想从Python PyUSB释放当前的USB设备。然后,我想在重置后将其重新连接到USB设备硬件。请让我知道,如何释放USB设备连接和接口…

在Pytorch中重复张量的特定列 - python

我有一个大小为X的pytorch张量m x n和一个长度为num_repeats的非负整数n列表(假定sum(num_repeats)> 0)。在forward()方法中,我想创建一个大小为X_dup的张量m x sum(num_repeats),其中i的列X重复num_repeats[i]次。张量X_dup将在forward()方法的下游使用,因此需…

Spacy如何将标记标签整体化? - python

在包含#标签(例如tweet)的句子中,spacy的令牌生成器将标签分为两个令牌:import spacy nlp = spacy.load('en') doc = nlp(u'This is a #sentence.') [t for t in doc] 输出:[This, is, a, #, sentence, .…