【问题标题】:Explode dataset based on a specific column in Python基于 Python 中的特定列展开数据集
【发布时间】:2022-01-20 19:29:17
【问题描述】:

我希望根据 Python 中的特定列展开我的数据集。

数据

id  type    date    stat    energy
aa  ss      Q1 2022 3       10
aa  ss      Q2 2022 2       10
bb  uu      Q1 2022 1       15
bb  uu      Q2 2022 3       15
cc  ii      Q1 2022 0       0
            

希望

id  type    date    stat    energy
aa  ss     Q1 2022  3       10
aa  ss     Q1 2022  3       10
aa  ss     Q1 2022  3       10
aa  ss     Q2 2022  2       10
aa  ss     Q2 2022  2       10
bb  uu     Q1 2022  1       15
bb  uu     Q2 2022  3       15
bb  uu     Q2 2022  3       15
bb  uu     Q2 2022  3       15
cc  ii     Q1 2022  0       0

正在做

df.explode(list['stat'])

欢迎提出任何建议

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    使用df.index.repeat:

    repeats = np.where(df['stat'] == 0, 1, df['stat'])
    # OR
    repeats = df['stat'].clip(lower=1)
    
    out = df.reindex(df.index.repeat(repeats)).reset_index(drop=True)
    print(out)
    
    # Output
       id type     date  stat  energy
    0  aa   ss  Q1 2022     3      10
    1  aa   ss  Q1 2022     3      10
    2  aa   ss  Q1 2022     3      10
    3  aa   ss  Q2 2022     2      10
    4  aa   ss  Q2 2022     2      10
    5  bb   uu  Q1 2022     1      15
    6  bb   uu  Q2 2022     3      15
    7  bb   uu  Q2 2022     3      15
    8  bb   uu  Q2 2022     3      15
    9  cc   ii  Q1 2022     0       0
    

    【讨论】:

    • 当然——谢谢你原来的soln作品——想知道编辑有什么变化吗? @corralien
    • 因为如果你重复一行零次,该行就会消失,所以我需要至少保留一个实例(你的行'cc')
    【解决方案2】:

    另一种解决方案可能是

    df['stat'] = [[x]*x if x > 0 else [x] for x in df['stat']]
    new = df.explode('stat')
    

    【讨论】:

      【解决方案3】:

      更快更简洁的方法是使用np.repeat

      m=df['stat'].ge(1)#Isolate rows to be duplicated
      df1 = (pd.DataFrame(np.repeat(df[m].values,df.loc[m,'stat'], axis=0)#convert to numpy array and duplicate conditionally
                          , columns=df.columns)#Convert back to df
             .append(df[~m])#Reappend rows that had had zero dup required
            )
      print(df1)
      

      【讨论】:

        猜你喜欢
        • 2021-09-12
        • 1970-01-01
        • 1970-01-01
        • 2019-06-19
        • 2016-01-28
        • 2015-12-01
        • 2022-07-08
        • 2017-04-28
        • 1970-01-01
        相关资源
        最近更新 更多