我想在python中的np.array中执行换行。我想要的是取数组的第一行并将其放在数组的末尾。我有代码可以交换两行,如下所示:
data_ask_bid = data_ask_bid[((0 <= data_ask_bid.index.weekday <= 3) | (data_ask_bid.index.weekday == 4 & data_ask_bid.index.hour < 22))]
但是这段代码执行第一行和最后一行之间的交换。我想把第一行放在最后。我怎么能这样做?
初始矩阵如下:
import numpy as np
my_array = np.arrange(25).reshape(5, 5)
print my_array, '\n'
def swap_rows(arr, frm, to):
arr[[frm, to],:] = arr[[to, frm],:]
//swap_rows(my_array, 0, 8)
//print my_array
my_array[-1] = my_array[0]
print my_array
预期结果如下:
[[ 0 1 2 3 4]
[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]]
编辑:我正在尝试在我的矩阵中执行相同的操作,如下所示:
但它不会改变任何事情。我的代码如下:
[[ 5 6 7 8 9]
[10 11 12 13 14]
[15 16 17 18 19]
[20 21 22 23 24]
[ 0 1 2 3 4]]
我得到了相同的数组。
答案 0 :(得分:1)
您可以使用np.roll
-
np.roll(my_array,-1,axis=0)
示例运行 -
In [53]: my_array
Out[53]:
array([[ 0, 1, 2, 3, 4, 5, 6, 7, 8],
[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80]])
In [54]: np.roll(my_array,-1,axis=0)
Out[54]:
array([[ 9, 10, 11, 12, 13, 14, 15, 16, 17],
[18, 19, 20, 21, 22, 23, 24, 25, 26],
[27, 28, 29, 30, 31, 32, 33, 34, 35],
[36, 37, 38, 39, 40, 41, 42, 43, 44],
[45, 46, 47, 48, 49, 50, 51, 52, 53],
[54, 55, 56, 57, 58, 59, 60, 61, 62],
[63, 64, 65, 66, 67, 68, 69, 70, 71],
[72, 73, 74, 75, 76, 77, 78, 79, 80],
[ 0, 1, 2, 3, 4, 5, 6, 7, 8]])