简体   繁体   English

如何在数组的开头添加一个值?

[英]How to add a value at the beginning of an array?

I want to add the value 0 at the beginning of an array.我想在数组的开头添加值 0 。

My code looks like:我的代码如下所示:

import numpy as np
import matplotlib.pyplot as plt
import math as m
import loaddataa as ld
import scipy.integrate as integrate 

dataListStride = ld.loadData("../Data/Fabienne")
indexStrideData = 0 
strideData = dataListStride[indexStrideData]

def horizontal(yAngle, yAcceleration, xAcceleration):
    a = (m.cos(yAngle)*yAcceleration)-(m.sin(yAngle)*xAcceleration)
    return a

resultsHorizontal = list()

for i in range (len(strideData)):
    strideData_yAngle = strideData.to_numpy()[i, 2]
    strideData_xAcceleration = strideData.to_numpy()[i, 4]
    strideData_yAcceleration = strideData.to_numpy()[i, 5]
    resultsHorizontal.append(horizontal(strideData_yAngle, strideData_yAcceleration, strideData_xAcceleration))

print("The values are: " +str(resultsHorizontal))

This is the output after the for - loop: output array Where the red arrow goes, a 0 should be added.这是for循环后的output: output数组红色箭头所在的地方,应该加一个0。 Could someone please tell me how I can reach this?有人可以告诉我如何做到这一点吗? Thanks for helping me.谢谢你帮助我。

To insert things at a specific position in an array, the following command works:要在数组中的特定 position 处插入内容,可以使用以下命令:

>>>my_array = np.arange(5, 14, 2)
>>>np.insert(my_array, 0, 0)
>>>print(my_array)
[0, 5, 7, 9, 11, 13]

So you could just use the np.insert() command after going through your for loop.因此,您可以在完成for循环后使用np.insert()命令。

You could either insert a 0 as suggested by Steven in their answer, or just start with a list which already has a 0 as the first element, like您可以按照 Steven 在他们的回答中建议的那样插入 0,或者只是从一个已经有 0 作为第一个元素的列表开始,比如

resultsHorizontal = [0]

Both approaches would yield the same result两种方法都会产生相同的结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM