Python 不同集合的熊猫分类

Python 不同集合的熊猫分类,python,pandas,dataframe,binning,Python,Pandas,Dataframe,Binning,我有一个棒球运动员的数据框架和他们的一些统计数据。比如说 id | position | gamesPlayed --------------------------------- 1 First Base 100 2 First Base 3 3 First Base 45 4 First Base 162 5 Second Base 145 6 Second Base 120 7

我有一个棒球运动员的数据框架和他们的一些统计数据。比如说

id    | position   |  gamesPlayed
---------------------------------
1      First Base    100
2      First Base    3
3      First Base    45
4      First Base    162
5      Second Base   145
6      Second Base   120
7      Second Base   6
8      Second Base   88
我可以通过执行以下操作将所有位置显示的游戏装箱:

labels = ['everyday','platoon','bench','scrub']
df['playingt_time'] = pd.qcut(df['gamesPlayed'], q=4, labels=labels)
但我更喜欢根据位置来标记比赛时间。我可以为每个职位这样做:

pt1B = pd.qcut(df[df['position']=='First Base']['gamesPlayed'], q=4,labels=bin_labels)
pt2B = pd.qcut(df[df['position']=='Second Base']['gamesPlayed'], q=4,labels=bin_labels)

但是,使用此播放时间标签更新数据帧是一个复杂但繁琐的过程,因为我必须完成以下步骤:

pt1B.rename("playing_time",inplace=True)
pt2B.rename("playing_time",inplace=True)
df['playing_time'] = ''
df.update(pt1B)
df.update(pt2B)

我相信有一种方法可以更简洁地做到这一点,但就我的一生而言,我就是没能弄明白!有什么建议吗?

我相信下面的代码应该可以工作。我在列表末尾添加了[:-1]以颠倒顺序

labels = ['everyday','platoon','bench','scrub'][::-1]

df['category'] = df.groupby('position')['gamesPlayed'].transform(lambda x: pd.qcut(x,q=4, labels=labels))

谢谢你!我知道这一定很简单。同样值得注意的是,在我的示例中,我将标签按错误的顺序放置,但在答案中,标签变量上的[::1]修复了这一问题。