【问题标题】:Efficiently reduce the size of groups in a dataframe有效减少数据框中组的大小
【发布时间】:2022-06-29 23:44:33
【问题描述】:

我有一个数据框,我使用 groupby 函数根据每行的名称对其进行分组。然后我想将每个组减少到给定的大小。然后,我将这些组重新添加到数据库中以用于其他进程。目前我正在 for 循环中执行此操作,但这似乎效率很低。有没有一种方法可以让 pandas 更有效地做到这一点?

grouped = df.groupby(['NAME'])

total = grouped.ngroups

df_final = pd.DataFrame()
for name, group in grouped:

    target_number_rows = 10

    if len(group.index) > target_number_rows:
        shortened = group[::int(len(group.index) / target_number_rows)]
        df_final = pd.concat([df_final, shortened], ignore_index=True)

【问题讨论】:

    标签: python pandas dataframe pandas-groupby


    【解决方案1】:

    按名称分组并应用sample(在该组中随机取 N),其中 N 是您想要的金额或该组的完整金额,例如:

    out = df.groupby('NAME').apply(lambda g: g.sample(min(len(g), target_number_rows)))
    

    否则取前N或后N,例如:

    out = df.groupby('NAME').head(target_number_rows)
    # or...
    out = df.groupby('NAME').tail(target_number_rows)
    

    【讨论】:

    • 我喜欢这个答案,但我希望在组中得到均匀分布的值(而不是随机的),因此是我目前使用的方法。可以这样做吗?
    • @James 怎么样:df.groupby('NAME').apply(lambda g: g if len(g) <= 10 else g[::len(g) // 10])
    猜你喜欢
    • 1970-01-01
    • 2023-04-01
    • 2018-01-31
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-17
    • 2016-11-11
    • 1970-01-01
    相关资源
    最近更新 更多