python - 为什么 pandas.cut() 在两种类似情况下的唯一计数表现不同?

标签 python pandas dataframe

在第一种情况下,我使用一个非常简单的 DataFrame 来尝试使用 pandas.cut() 来计算一个范围内的一列中的唯一值的数量另一列。代码按预期运行:

enter image description here

但是,在下面的代码中,pandas.cut() 计算唯一值的数量是错误的。我希望第一个 bin (1462320000, 1462406400] 有 5 个唯一值,而其他 bin 包括最后一个 bin (1462752000, 1462838400] 有 0 个唯一值。

相反,如结果所示,代码在最后一个 bin 中返回 5 个唯一值(1462752000、1462838400),而突出显示的 2 个值不应计算在内,因为它们超出范围。

enter image description here

那么谁能解释为什么 pandas.cut() 在这两种情况下表现如此不同?此外,如果您还可以告诉我如何更正代码以正确计算一列中另一列值范围内的唯一值的数量,我将非常感激。


附加信息:(请导入 pandasnumpy 来运行代码,我的 pandas 版本是 0.19.2,我正在使用 python 2.7)

为了方便您引用,我特此发布我的DataFrame 和代码,供您重现我的代码:

案例一:

df = pd.DataFrame({'No': [1,1.5,2,1,3,5,10], 'useragent': ['a', 'c', 'b', 'c', 'b','a','z']})
print type(df)
print df
df.groupby(pd.cut(df['No'], bins=np.arange(0,4,1))).useragent.nunique()

案例二:

print type(df)
print len(df)
print df.time.nunique()
print df.hash.nunique()
print df[['time','hash']]
df.groupby(pd.cut(df['time'], bins =np.arange(1462320000,1462924800,86400))).hash.nunique()

案例 2 的数据:

time      hash
1462328401 qo
1462328401 qQ
1462838401 q1
1462328401 q1
1462328401 qU
1462328401 qU
1462328401 qU
1462328401 qU
1462328401 qX
1462838401 qX

最佳答案

这似乎是一个 bug .

举个简单的例子:

In [50]: df=pd.DataFrame({'atime': [28]*8+[38]*2, 'hash':randint(0,3,10)}
).sort_values('hash')
Out[50]: 
      atime  hash
1     28     0
3     28     0
4     28     0
5     28     0
8     38     0
2     28     1
6     28     1
0     28     2
7     28     2
9     38     2 

In [50bis;)]: df.groupby(pd.cut(df.atime,bins=arange(27,40,2))).hash.unique()
Out[50bis]: 
atime
(27, 29]                   [0, 1, 2]   # ok
(29, 31]                          []
(31, 33]                          []
(33, 35]                          []
(35, 37]                          []
(37, 39]                      [0, 2]
Name: hash, dtype: object

In [51]: df.groupby(pd.cut(df.atime,bins=arange(27,40,2))).hash.nunique()
Out[51]: 
atime
(27, 29]    2 # bug
(29, 31]    0
(31, 33]    0
(33, 35]    0
(35, 37]    0
(37, 39]    2
Name: hash, dtype: int64

这似乎是一个有效的解决方法,将切割结果转换为列表:

In [52]: df.groupby(pd.cut(df.atime,bins=arange(27,40,2)).tolist()
).hash.nunique()
Out[52]: 
atime
(27, 29]    3
(37, 39]    2
Name: hash, dtype: int64

关于python - 为什么 pandas.cut() 在两种类似情况下的唯一计数表现不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42347173/

相关文章:

python - 如何将矩阵中沿列的每个最大值更改为 1,其他值更改为 0?

python - 将函数应用于数据帧以创建列表的矢量化方式

python - 添加不同大小的 pandas DataFrame 的值

python - 为什么使用索引匹配列将 Series 连接到 DataFrame 不起作用?

python - 使用点分隔字符串的动态字典值访问

python - 请求中包含的安全 token 无效。当没有指定配置文件时

python - Python 中滚动相关数据框的滚动平均值?

python - 从 Pandas apply 获取两个返回值

python - DataFrame 运行计数和连接

python - 使用 sqlalchemy 从 mysql 一次输出一行数据