【问题标题】:Reset index of grouped data frames重置分组数据帧的索引
【发布时间】:2023-01-12 16:57:10
【问题描述】:

我想重置分组数据帧的索引,并根据示例,我写了:

for name, df_group in df.groupby('BL', as_index=False):
    print(df_group)

但输出显示索引尚未重置。

      Num               BL  Home  Requester
4   16986  140080043863936     5          5
5   16987  140080043863936     0          5
10  16986  140080043863936     7          5

我该如何解决?

【问题讨论】:

  • 索引在循环之后而不是在循环期间被删除。在循环中,您有一片原始数据帧。并且只有在使用applyagg等时才有效。

标签: python pandas


【解决方案1】:

groupbyas_index=False 选项对 groupby 方法很有用(它防止石斑鱼成为新索引并将其保留为一列),而不是在手动循环组时。

你必须在这里reset_index

for name, df_group in df.groupby('BL'):
    print(df_group.reset_index(drop=True))

【讨论】:

    【解决方案2】:

    as_index=False并不是说最后给出0,1,...N个索引结果;这意味着不要将石斑鱼放在索引中,而是放在列中,即在您的情况下为“BL”。您可以在循环中显式重置索引:

    for name, df_group in df.groupby("BL"):
        print(df_group.reset_index(drop=True))
    

    【讨论】:

      【解决方案3】:

      我会尝试: print(df_group.reset_index(drop=True)

      【讨论】:

        猜你喜欢
        • 2020-04-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-12
        • 2018-03-09
        • 2019-08-12
        • 1970-01-01
        • 2020-12-21
        相关资源
        最近更新 更多