wee*_*qg3 6 python dataframe pandas
在第一种情况下,我使用一个非常简单的方法DataFrame来尝试使用pandas.cut()来计算另一列范围内一列中的唯一值的数量.代码按预期运行:
但是,在以下代码中,pandas.cut()计算错误的唯一值的数量.我希望第一个bin(1462320000,1462406400)有5个唯一值,其他bin包括最后一个bin(1462752000,1462838400)有0个唯一值.
相反,如结果所示,代码在最后一个bin(1462752000,1462838400)中返回5个唯一值,而不应计算2个突出显示的值,因为它们超出范围.
所以有人可以解释为什么pandas.cut()在这两种情况下表现如此不同?而且,如果您还能告诉我如何更正代码以正确计算另一列的值范围内的一列中的唯一值的数量,我将非常感激.
附加信息:(请导入pandas并numpy运行代码,我的pandas版本是0.19.2,我使用的是python 2.7)
为了您的参考,我特此发布我DataFrame和您的代码以重现我的代码:
情况1:
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()
Run Code Online (Sandbox Code Playgroud)
案例2:
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()
Run Code Online (Sandbox Code Playgroud)
案例2的数据:
time hash
1462328401 qo
1462328401 qQ
1462838401 q1
1462328401 q1
1462328401 qU
1462328401 qU
1462328401 qU
1462328401 qU
1462328401 qX
1462838401 qX
Run Code Online (Sandbox Code Playgroud)
这似乎是一个错误。
举一个简单的例子:
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
Run Code Online (Sandbox Code Playgroud)
这似乎是一个有效的解决方法,将剪切结果转换为列表:
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
Run Code Online (Sandbox Code Playgroud)