如何解决Pandas:拆开滑动窗口?
我有一个 110 万行的数据框,需要按以下滚动方式处理:
假设窗口大小为 2
000
001
002
003
010
011
012
013
020
021
022
023
030
031
032
033
输出将是:
A B
0 "This" 3
1 "is" 4
2 "a" 5
3 "test" 6
我目前正在通过遍历数据框来执行此操作,但处理如此大的数据集需要 3 个小时。
有没有更有效的方法来做到这一点?
解决方法
一个想法有strides和单独广播每一列,因为不同的类型:
def rolling_window(a,window):
shape = a.shape[:-1] + (a.shape[-1] - window + 1,window)
strides = a.strides + (a.strides[-1],)
return np.lib.stride_tricks.as_strided(a,shape=shape,strides=strides)
N = 2
a = rolling_window(np.arange(len(df)),N)
print (a)
[[0 1]
[1 2]
[2 3]]
df = pd.concat([pd.DataFrame(df[x].to_numpy()[a]).rename(columns=lambda y: f'{x}_{y + 1}')
for x in df.columns],axis=1)
print (df)
A_1 A_2 B_1 B_2
0 This is 3 4
1 is a 4 5
2 a test 5 6
如果需要3
:
N = 3
a = rolling_window(np.arange(len(df)),N)
print (a)
[[0 1 2]
[1 2 3]]
df = pd.concat([pd.DataFrame(df[x].to_numpy()[a]).rename(columns=lambda y: f'{x}_{y + 1}')
for x in df.columns],axis=1)
print (df)
A_1 A_2 A_3 B_1 B_2 B_3
0 This is a 3 4 5
1 is a test 4 5 6
在 numpy 解决方案中的表现很好:
#8 columns,400krows
df = pd.concat([df] * 4,ignore_index=True,axis=1)
df.columns = list('ABCDEFGH')
df = pd.concat([df] * 100000,ignore_index=True)
In [53]: %%timeit
...: a = rolling_window(np.arange(len(df)),2)
...: pd.concat([pd.DataFrame(df[x].to_numpy()[a]).rename(columns=lambda y: f'{x}_{y + 1}') for x in df.columns],axis=1)
...:
...:
167 ms ± 741 µs per loop (mean ± std. dev. of 7 runs,10 loops each)
In [54]: %%timeit
...: window = 2
...: pd.DataFrame({ f'{col}_{i}': list(df[col][i-1:len(df)-window+i]) for col in df.columns for i in range(1,window+1) })
...:
...:
1.52 s ± 2.61 ms per loop (mean ± std. dev. of 7 runs,1 loop each)
,
Java 支持匿名数组的特性,因此在向方法传递数组时不需要声明数组。
代码
//@GIOCHE
公共类 TestAnonymousArray{
/创建一个接收方法
数组作为参数/
static void printArray(int arr[])
{
for(int i = 0; i
System.Out.Println(arr[i]);
}
public static void main(String args[]) {
//将匿名数组传递给方法
printArray(new int[] {10,22,44,66});
输出 10 22 44 66
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。