【问题标题】:How to multiply the numbers 0 to 150 by the same value?如何将数字 0 到 150 乘以相同的值?
【发布时间】:2020-06-10 10:48:20
【问题描述】:

我的 Python 练习有问题。

这是我的代码的一部分:

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

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

plt.plot(resultsHorizontal)

print(len(resultsHorizontal))

还有loaddataa.py的代码:

import os
import pandas as pd

def loadData(relativPath):
    files = os.listdir(relativPath)
    path = os.path.abspath(relativPath)
    datas = list()
    for file in files:
        absPath = path + "/" + file
        print(absPath)
        data = pd.read_csv(absPath)
        datas.append(data)
    return datas

通过def horizontal 的计算,我最终得到了很多值。有了print(len(resultsHorizontal)),我知道有多少价值。在此示例中或在此处读取 CSV,我得到 150 个值。 情节如下所示: enter image description here

如您所见,x 轴由 0 到 150 的值组成,因为 CSV 列表中有 150 个计算值。我想计算 x 轴上的每个值乘以 0.01。因此计算如下所示: 0 * 0.01= 0, 1*0.01=0.01, 2*0.01=0.02, .... , 20*0.01=0.2 ,.... ,149*0.01=1.49, 150* 0.01=1.5。 = 之后的值应该在 x 轴上。 还有一个问题。它应该独立于 150,因为它可能会发生多于或少于 150 个值。这取决于导入的 CSV 文件。我希望很清楚我的问题是什么。谢谢你帮助我。

【问题讨论】:

    标签: python list numpy matplotlib


    【解决方案1】:

    听起来您想缩放 x 轴值。 您的绘图代码没有明确指定 x 轴。 plt.plot(resultsHorizontal)

    你可以这样做

    import numpy as np
    import matplotlib.pyplot as plt
    
    scale_factor = 0.01
    x_values = np.arange(len(resultsHorizontal)) * scale_factor
    plt.plot(x_values, resultsHorizontal)
    

    如果您想阻止 matplotlib 自动重新缩放 x 轴以适应您的压缩信号:

    plt.xlim([0, len(resultsHorizontal)])
    

    否则 matplotlib 将调整 x 轴以适应数据。

    【讨论】:

      【解决方案2】:

      如果你的列表是一个 numpy 数组,那么你可以将它乘以 0.01 来得到结果,但是如果你出于某种原因想将它保留为 python 列表,那么一个简单的列表推导很容易解决这个问题。

      new_ret = [0.01 * value for value in resultsHorizontal]
      

      `

      【讨论】:

        猜你喜欢
        • 2019-12-07
        • 2021-06-25
        • 2015-12-05
        • 1970-01-01
        • 2018-10-08
        • 2016-01-03
        • 2017-03-27
        • 2018-03-14
        • 1970-01-01
        相关资源
        最近更新 更多