【问题标题】:Move N elements in array from back to front将数组中的 N 个元素从后向前移动
【发布时间】:2019-01-07 19:39:23
【问题描述】:

我有一个包含 2 列的文本文件,我需要选择其中的一列作为数组 其中包含 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,) 

有什么帮助吗??

【问题讨论】:

    标签: arrays python-3.x slice python-import


    【解决方案1】:

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

    new_array = np.roll(2nd_column, cut)
    

    【讨论】:

      【解决方案2】:

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

      其中一种方法是使用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. 不应以数字开头命名变量

      【讨论】:

      • 如何直接操作我的cut?我试过这样做,但它不起作用!
      • 就像我在上面的 sn-p 中所做的那样。您可以直接使用2nd_columns_array,并且代码中不再需要remain_pointscut_points 这两个变量。
      • @ machnic- 运行良好。非常感谢您的帮助。
      猜你喜欢
      • 1970-01-01
      • 2012-08-25
      • 1970-01-01
      • 1970-01-01
      • 2022-01-05
      • 2017-12-14
      • 1970-01-01
      • 2013-05-17
      • 2016-04-25
      相关资源
      最近更新 更多