语境 :
我想了解如何top
describe()
的属性在 python (3.7.3) 中工作 pandas
(0.24.2)。
至今的努力 :
If multiple object values have the highest count, then the count and top results will be arbitrarily chosen from among those with the highest count.
我试图了解代码的哪一部分完全归因于“任意”输出。
describe
正在调用的代码反过来。我的回溯如下:
describe() #pandas.core.generic
describe_1d() #pandas.core.generic
describe_categorical_1d() #pandas.core.generic
value_counts() #pandas.core.base
value_counts() #pandas.core.algorithms
_value_counts_arraylike() #pandas.core.algorithms
# In the above step it uses hash-table, to find keys and their counts
# I am not able to step further, as further implementations are in C.
sample 试用 :
import pandas as pd
sample = pd.Series(["Down","Up","Up","Down"])
sample.describe()["top"]
上面的代码可以给出
Down
或 Up
随机,正如预期的那样。问题 :
如果是,
-- 不是每次都相同的键具有相同的哈希值并以相同的顺序获取吗?
-- 键是如何散列、迭代(用于获取所有键)和从哈希表中获取的?
任何指针都非常感谢!提前致谢 :)
最佳答案
正如上面所指出的,它是任意给出“向下”的,但不是随机给出的。在具有相同 Pandas 版本的同一台机器上,运行上面的代码应该总是产生相同的结果(尽管文档不保证,请参阅下面的评论)。
让我们重现正在发生的事情。
鉴于这个系列:
abc = pd.Series(list("abcdefghijklmnoppqq"))
value_counts implementation归结为:
import pandas._libs.hashtable as htable
keys, counts = htable.value_count_object(np.asarray(abc), True)
result = pd.Series(counts, index=keys)
结果:
g 1
e 1
f 1
h 1
o 1
d 1
b 1
q 2
j 1
k 1
i 1
p 2
n 1
l 1
c 1
m 1
a 1
dtype: int64
结果的顺序由哈希表的实现给出。每次调用都是一样的。
您可以查看 value_count_object 的实现, 调用 build_count_table_object, 其中 uses khash implementation以获取有关散列的更多详细信息。
计算完表后,value_counts 实现为 sorting快速排序的结果。这种排序并不稳定,使用这个特殊构造的示例重新排序“p”和“q”:
result.sort_values(ascending=False)
q 2
p 2
a 1
e 1
f 1
h 1
o 1
d 1
b 1
j 1
m 1
k 1
i 1
n 1
l 1
c 1
g 1
dtype: int64
因此,排序可能有两个因素:首先是散列,其次是非稳定排序。
显示的最高值就是 first entry排序列表,在这种情况下,“q”。
在我的机器上,快速排序在 17 个条目时变得不稳定,这就是我选择上面示例的原因。
我们可以通过这种直接比较来测试非稳定排序:
pd.Series(list("abcdefghijklmnoppqq")).describe().top
'q'
pd.Series(list( "ppqq")).describe().top
'p'
关于python - 当多个元素具有最高计数时,pandas describe() - top 如何工作?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56443324/