将数组中的 N 个元素从后向前移动

Move N elements in array from back to front

我有一个包含 2 列的文本文件,我需要 select 将其中的一列作为数组 其中包含 200000 并从此数组中剪切 N 个元素并将它们从后向前移动。

我使用了以下代码:

import numpy as np
import glob

files = glob.glob("input/*.txt")

for file in files:
     data_file = np.loadtxt(file)
     2nd_columns = data_file [:,1]
     2nd_columns_array = np.array(2nd_columns)

cut = 62859  # number of elements to cut
remain_points = 2nd_columns_array[:cut]
cut_points = 2nd_columns_array[cut:]
new_array = cut_points + remain_points

它不起作用并出现以下错误:

ValueError: operands could not be broadcast together with shapes (137141,) (62859,) 

有什么帮助吗??

它不起作用,因为您试图添加存储在两个数组中的值,并且它们具有不同的形状。

其中一种方法是使用 numpy.hstack:

new_array = np.hstack((2nd_columns_array[cut:], 2nd_columns_array[:cut]))

旁注:

  1. 使用您的代码,您将仅重新排序最后一个文件的第 2 列,因为重新排序在 for 循环之外
  2. 您不需要将 cut_poinstsremain_points 存储在单独的变量中。可以直接在2nd_columns_array
  3. 上操作
  4. 你不应该从数字开始命名变量

此过程的一个简单方法是 numpy.roll

new_array = np.roll(2nd_column, cut)