【问题标题】:Pandas Binning for different sets针对不同集合的 Pandas Binning
【发布时间】:2020-06-25 16:10:38
【问题描述】:

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

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

我可以通过执行以下操作将所有位置的 gamesPlayed 合并:

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)

我确信有一种方法可以更简洁地做到这一点,但对于我的生活,我只是无法弄清楚!有什么建议吗?

【问题讨论】:

    标签: python pandas dataframe binning


    【解决方案1】:

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

    labels = ['everyday','platoon','bench','scrub'][::-1]
    
    df['category'] = df.groupby('position')['gamesPlayed'].transform(lambda x: pd.qcut(x,q=4, labels=labels))
    

    【讨论】:

    • 谢谢!知道它必须是一件容易的事。另请注意,我在示例中将标签按错误顺序放置,但这已在标签变量上的 [::1] 的答案中修复。
    猜你喜欢
    • 2022-12-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多