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]
添加回答
舉報