我的数据框架如下:
df = pd.DataFrame([['A', 'a', 'web'],
['A', 'b', 'mobile'],
['B', 'c', 'web'],
['C', 'd', 'web'],
['D', 'e', 'mobile'],
['D', 'f', 'web'],
['D', 'g', 'web'],
['D', 'g', 'web']],
columns=['seller_id', 'item_id', 'selling_channel'])
它显示了已售出的商品,其中包含关于谁是卖家以及用于销售商品的销售渠道(在上面的示例中,可以是网络或移动渠道,但实际数据中有更多潜在渠道)的信息
我想确定哪一个销售渠道是给定销售id的主要渠道,但还有其他限制:
mixed
因此,对于上面的输入,我期待以下输出:
df = pd.DataFrame([['A', 'mixed'],
['B', 'web'],
['C', 'web'],
['D', 'web']],
columns=['seller_id', 'main_selling_channel'])
现在,我正在通过手动迭代每个数据帧的行来构建映射,其中每个卖方id列出了每个通道以及它的出现次数。然后我再次迭代该数据,以确定哪个通道是主通道。但是当我有10k行输入时,这个手动迭代已经花费了很多时间——而实际数据包含数百万条输入
我想知道是否有什么有效的方法可以用pandas api而不是手动迭代
这不是一种优雅的方式,但却能做到:
这里有一种方法,使用
df.groupby
和normalize=True
的值计数来检查每组值的pct,然后检查%是否大于或等于0.75,然后使用np.where
设置返回Tue到mixed
的值,最后df.groupby()
和idxmax
将返回1个值,否则mixed
相关问题 更多 >
编程相关推荐