>我有一个熊猫数据帧,并且仅当该客户编号出现超过设定的次数时,我才希望返回数据帧。
下面是数据帧的示例:
114 2017-04-26 1 7507 34 13
115 2017-04-26 3 77314 41 14
116 2017-04-27 7 4525 190 315
117 2017-04-27 7 5525 67 94
118 2017-04-27 1 6525 43 378
119 2017-04-27 3 7415 38 27
120 2017-04-27 2 7613 47 10
121 2017-04-27 2 77314 9 3
122 2017-04-28 1 227 17 4
123 2017-04-28 8 4525 205 341
124 2017-04-28 1 7415 31 20
125 2017-04-28 2 77314 8 2
如果该客户出现超过 5 次,请使用以下代码:
print(zip_data_df['Customers'].value_counts()>5)
7415 True
4525 True
5525 True
77314 True
6525 True
4111 True
227 True
206 False
7507 False
7613 False
4108 False
3046 False
2605 False
4139 False
4119 False
现在我期望如果我这样做:
print(zip_data_df[zip_data_df['Customers'].value_counts()>5])
它会向我显示出现超过 5 次的客户的完整数据帧,但我得到了布尔错误。我意识到为什么它现在给我一个错误:一个数据帧只是告诉我该客户编号是否出现超过 5 次,而另一个数据帧每次出现客户编号时都会显示我。它们的长度不匹配。但是,如何获取它,以便数据帧仅返回该客户出现超过 5 次的记录?
我确信我忽略了一些简单的答案,但我感谢您能为我提供的任何帮助。
所以这里的问题是索引:value_counts(( 返回一个在"客户"上索引的系列,而zip_data_df似乎在其他东西上索引。您可以执行以下操作:
cust_counts = zip_data_df['Customers'].value_counts().rename('cust_counts')
zip_data_df = zip_data_df.merge(cust_counts.to_frame(),
left_on='Customers',
right_index=True)
从那里,您可以从zip_data_df有条件地选择,如下所示:
zip_data_df[zip_data_df.cust_counts > 5]
我遇到了类似的问题,并以这种方式解决了它。
cust_counts = zip_data_df['Customers'].value_counts()
cust_list = cust_counts[cust_counts > 5].index.tolist()
zip_data_df = zip_data_df[zip_data_df['Customers'].isin(cust_list)]
你要找的是:
zip_data_df['Customers'].value_counts()[zip_data_df['Customers'].value_counts()>5]
一个方便的小groupby转换来完成工作
subset_customers_df = zip_data_df[
zip_data_df.groupby('Customers')
['Customers'].transform('size')>5]
适用于熊猫 0.25.3
# create the boolean series
s1 = pd.series(zip_data_df['Customers'].value_counts())
# select rows that are greater than 5
result = [i for i,j in zip(s1.index,s1.value) if j>5]
# select rows based values in the result list
zip_data_df[zip_data_df.Customers.isin(result)]
这对我有用,虽然写这么长的代码很蹩脚,但它比一行更容易理解
没有尝试过,但这应该有效:
cust_by_size = zip_data_df.groupBy("Customers").size()
cust_index_gt_5 = cust_by_size.index[cust_by_size > 5]
zip_data_cust_index_gt_5 = zip_data_df[zip_data_df["Customers"].isin(cust_index_gt_5)]