mha*_*ger 19 python group-by pandas
有没有办法构建Pandas groupby和qcut命令返回一个具有嵌套切片的列?具体来说,假设我有2组数据,我希望qcut应用于每个组,然后将输出返回到一列.这类似于MS SQL Server的ntile()命令,允许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.
unu*_*tbu 37
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