2 回答

TA贡献1824条经验 获得超8个赞
您可以通过1行代码来实现这一点。这是一个例子
import pandas as pd
a = pd.DataFrame([
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r']
])
现在将数据帧移动 1 行并连接它们
a_1 = a.shift(-1)
a_2 = a.shift(-2)
c = pd.concat([a, a_1, a_2], axis=1)
然后更正新数据帧中的行
c = c.iloc[:-2]
完整代码如下
a = pd.DataFrame([
['a', 'b', 'c'],
['d', 'e', 'f'],
['g', 'h', 'i'],
['j', 'k', 'l'],
['m', 'n', 'o'],
['p', 'q', 'r']
])
b = pd.concat([a, a.shift(-1), a.shift(-2)], axis=1).iloc[:-2]
print(a)
print(b)
不要忘记重命名索引和列。

TA贡献1802条经验 获得超4个赞
您可以通过numpy.ravel
使用具有扁平值的步幅,最后通过索引选择每行:3th
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)
a = rolling_window(df.to_numpy().ravel(), 9)[::3]
print (a)
[['a' 'b' 'c' 'd' 'e' 'f' 'g' 'h' 'i']
['d' 'e' 'f' 'g' 'h' 'i' 'j' 'k' 'l']
['g' 'h' 'i' 'j' 'k' 'l' 'm' 'n' 'o']
['j' 'k' 'l' 'm' 'n' 'o' 'p' 'q' 'r']]
df = pd.DataFrame(a)
print (df)
0 1 2 3 4 5 6 7 8
0 a b c d e f g h i
1 d e f g h i j k l
2 g h i j k l m n o
3 j k l m n o p q r
一般解决方案:
N = 3
M = len(df.columns)
a = rolling_window(df.to_numpy().ravel(), M*N)[::M]
添加回答
举报