简体   繁体   中英

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

I want to add the value 0 at the beginning of an array.

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. 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:

>>>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.

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

resultsHorizontal = [0]

Both approaches would yield the same result

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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