pandas groupby 和 qcut [英] Pandas groupby and qcut
本文介绍了 pandas groupby 和 qcut的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法构造 Pandas groupby 和 qcut 命令以返回具有嵌套图块的列?具体来说,假设我有 2 组数据,并且我希望将 qcut 应用于每组,然后将输出返回到一列.这类似于 MS SQL Server 的 ntile() 命令,它允许 Partition by().
Is there a way to structure Pandas groupby and qcut commands to return one column that has nested tiles? Specifically, suppose I have 2 groups of data and I want qcut applied to each group and then return the output to one column. This would be similar to MS SQL Server's ntile() command that allows Partition by().
A B C
0 foo 0.1 1
1 foo 0.5 2
2 foo 1.0 3
3 bar 0.1 1
4 bar 0.5 2
5 bar 1.0 3
在上面的数据框中,我想将 qcut 函数应用于 B,同时在 A 上进行分区以返回 C.
In the dataframe above I would like to apply the qcut function to B while partitioning on A to return C.
推荐答案
import pandas as pd
df = pd.DataFrame({'A':'foo foo foo bar bar bar'.split(),
'B':[0.1, 0.5, 1.0]*2})
df['C'] = df.groupby(['A'])['B'].transform(
lambda x: pd.qcut(x, 3, labels=range(1,4)))
print(df)
收益
A B C
0 foo 0.1 1
1 foo 0.5 2
2 foo 1.0 3
3 bar 0.1 1
4 bar 0.5 2
5 bar 1.0 3
这篇关于 pandas groupby 和 qcut的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文