如何将数据框中的每一行乘以 csv 文件中的值

How to multiply every row in dataframe by value from csv file

这是我的 csv 文件 CSV

我试图取“角度最小值”和“角度最大值”列的平均值,然后将结果数据框中的每一行乘以单元格 D8 中的“角度转换因子”。同样,我想对“最小扭矩”和“最大扭矩”执行相同的操作(获取平均值,然后将结果数据帧乘以单元格 E8 中的“扭矩转换因子”)。

到目前为止,这是我的代码:

import matplotlib.pyplot as plt                 
from matplotlib.pyplot import show, plot                                            
import numpy as np
from scipy.signal import savgol_filter
import os


def Torque_Analysis(filename):

    #Importing CSV Data and Defining 'AngleDF' and 'TorqueDF'

    Angle_Data = ['Angle Min' , 'Angle Max']                                                                
    Torque_Data = ['Torque Min' , 'Torque Max']
    AngleCol = ['Angle Conversion Factor']
    TorqueCol = ['Torque Conversion Factor']

    AngleConvFactor = pd.read_csv(filename, skiprows=6, usecols = AngleCol, nrows = 1, engine='python')
    TorqueConvFactor = pd.read_csv(filename, skiprows=6, usecols = TorqueCol, nrows = 1, engine='python')

    AngleDF = pd.read_csv(filename, skiprows=17,usecols=Angle_Data, skipfooter=4, engine='python')
    TorqueDF = pd.read_csv(filename, skiprows=17,usecols=Torque_Data, skipfooter=4, engine='python')

    #Calculating the average of 'Angle Min', 'Angle Max'

    col = AngleDF.loc[: ,'Angle Min':'Angle Max']                                                           
    AngleDF['Angle Mean'] = col.mean(axis=1)
    AngleDFmean= AngleDF['Angle Mean']

    #Calculating the average of 'Torque Min', 'Torque Max'

    col = TorqueDF.loc[: ,'Torque Min':'Torque Max']            
    TorqueDF['Torque Mean'] = col.mean(axis=1)
    TorqueDFmean= TorqueDF['Torque Mean']

    #Multiplying Torque Mean values by Torque conversion factor

    TorqueDFmean[:] = TorqueConvFactor * TorqueDFmean

    #Multiplying Angle Mean values by Angle conversion factor

    AngleDFmean[:] = AngleConvFactor * AngleDFmean  

我一直收到错误消息

“ValueError:无法使用长度与值不同的切片索引器进行设置”。

您的 AngleConcFactorTorqueConvFactor 在您的代码中保持为 1x1 DataFrame。 只需稍微清理一下您的功能就可以满足您的需求:

def Torque_Analysis(filename):
    Angle_Data = ['Angle Min' , 'Angle Max']                                                                
    Torque_Data = ['Torque Min' , 'Torque Max']
    AngleCol = ['Angle Conversion Factor']
    TorqueCol = ['Torque Conversion Factor']

    AngleConvFactor = pd.read_csv(filename, skiprows=6, usecols=AngleCol, nrows=1, engine='python').iat[0,0]
    TorqueConvFactor = pd.read_csv(filename, skiprows=6, usecols=TorqueCol, nrows=1, engine='python').iat[0,0]

    AngleDF = pd.read_csv(filename, skiprows=17, usecols=Angle_Data, skipfooter=4, engine='python')
    TorqueDF = pd.read_csv(filename, skiprows=17, usecols=Torque_Data, skipfooter=4, engine='python')

    AngleDF["Angle Mean"] = AngleDF[["Angle Min", "Angle Max"]].mean(axis=1)*AngleConvFactor
    TorqueDF["Torque Mean"] = TorqueDF[['Torque Min', "Torque Max"]].mean(axis=1)*TorqueConvFactor

请注意,我已使用 .iat[0,0] 将您的 1x1 数据帧转换为标量值。