熊猫按单元格值分解数据框

时间:2021-05-18 11:02:29

标签: pandas dataframe data-science data-munging

I 来自数据帧:

df = C1 C2 C3 from_time to_time
     a   b c     1         3
     q   t y     4         9

我想通过 from_time , to_time 的值来爆炸它,所以它会是:

df = C1 C2 C3 time from_time to_time
     a   b c    1      1         3
     a   b c    2      1         3
     a   b c    3      1         3
     q   t y    4      4         9
     q   t y    5      4         9

...

这样做的最佳方法是什么? 谢谢

1 个答案:

答案 0 :(得分:0)

如果数据帧较小,则将 DataFrame.exploderange 一起使用:

df.insert(3, 'time', df.apply(lambda x: range(x.from_time, x.to_time + 1), axis=1))
df = df.explode('time')
print (df)
  C1 C2 C3 time  from_time  to_time
0  a  b  c    1          1        3
0  a  b  c    2          1        3
0  a  b  c    3          1        3
1  q  t  y    4          4        9
1  q  t  y    5          4        9
1  q  t  y    6          4        9
1  q  t  y    7          4        9
1  q  t  y    8          4        9
1  q  t  y    9          4        9

为了获得更好的性能,将 Index.repeatDataFrame.loc 结合使用,对于新列,将 GroupBy.cumcount 用于每个索引值的计数器,并具有 from_time 值:

df = df.loc[df.index.repeat(df.to_time.sub(df.from_time) + 1)]
df.insert(3, 'time', df.groupby(level=0).cumcount().add(df['from_time']))
print (df)
  C1 C2 C3  time  from_time  to_time
0  a  b  c     1          1        3
0  a  b  c     2          1        3
0  a  b  c     3          1        3
1  q  t  y     4          4        9
1  q  t  y     5          4        9
1  q  t  y     6          4        9
1  q  t  y     7          4        9
1  q  t  y     8          4        9
1  q  t  y     9          4        9