问题描述
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
...
这样做的最佳方法是什么? 谢谢
解决方法
如果数据帧较小,则将 DataFrame.explode
与 range
一起使用:
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.repeat
与 DataFrame.loc
结合使用,对于新列,将 GroupBy.cumcount
用于每个索引值的计数器,并具有 from_time
值:
df = df.loc[df.index.repeat(df.to_time.sub(df.from_time) + 1)]
df.insert(3,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