首页 > 解决方案 > Python中的循环:如何在循环中应用相同的代码集

问题描述

感谢您在我之前的问题中提供的所有帮助。现在它引导我完成我最后的也是最困难的任务。让我分解一下:

我有一个名为:“PCU1-160321.csv”的文件

然后我运行以下代码(见下文),帮助我完成我需要做的各种事情。

这让我面临最困难的任务,即一次又一次地对其他 23 个文件执行相同的代码集(见下文),名为:

PCU 2 -160321.csv PCU 3 -160321.csv ... PCU 24 -160321.csv

例如。我想为 PCU2-160321.csv 调用 df2,为 PCU3-160321.csv 调用 df3 等。(因此,循环......)

还是有更好的循环方法?

下面我附上可视化: 在此处输入图像描述

非常感谢。

更新:我确实尝试过这样的事情,但它没有用...... 在此处输入图像描述

#Assign file names
file1 = 'PCU1-160321.csv'
file_out1 = file1+'15min.csv'

#Read csv file and assign header
df1 = pd.read_csv(gdrive_url+file1+'.csv', sep=';', names=['Date','Time_Decimal','Parameter','Value'])

#To split the Time_Decimal column and concatenate the second decimals back into Time column, and rearrange the column order
df1[['Time','DecimalSecond']] = df1.Time_Decimal.str.split(".",expand=True)
df1 = df1[['Date', 'Time', 'DecimalSecond', 'Parameter','Value']]

#Split AM and concatenate DecimalSecond
df1[['Time', 'AMPM']] = df.Time.str.split(" ", expand=True)
df1 = df1[['Date', 'Time', 'AMPM', 'DecimalSecond', 'Parameter','Value']]
df1['Time'] = df1['Time'].map(str) + '.' + df1['DecimalSecond'].map(str) + ' ' + df['AMPM'].map(str)
df1['Timestamp'] = df1['Date'].map(str) + ' ' + df1['Time']
df1 = df1[['Timestamp', 'Parameter','Value']]

#Assign index and set index as timestamp object
df1['Timestamp'] = pd.to_datetime(df1['Timestamp'])
df1 = df1.set_index('Timestamp')

#Assigning parameters I want to filter out of the df above.
Parameter1 = 'DCA_L_1'
Parameter2 = 'DCA_L_2'

#Filtering based on the variables defined above, contains whatevr parameter I need.
df1_param1 = df1[df1['Parameter'].str.contains(Parameter1)]
df1_param2 = df1[df1['Parameter'].str.contains(Parameter2)]

#Renaming the columns header
df1_param1.columns = ['Par1','Val1']
df1_param2.columns = ['Par2','Val2']

#Obtain exact name of parameter into a string, then we use this for the new df top row
par1 = df1_param1.head(1)['Par1'].values[0]
par2 = df1_param2.head(1)['Par2'].values[0]

#Downsampling 15 mins
df1_param1 = df1_param1.resample('15min').mean()
df1_param2 = df1_param2.resample('15min').mean()

#Concatenating all the dfs - except empty df, df_ppc_param4
df1_concat = pd.concat([df1_param1, df1_param2], axis=1)

#Select Values
df1_concat = df1_concat[['Val1','Val2']

#Rename columns to the new df_concat
df1_concat.columns = [par1,par2]

#To save output as csv
df_concat.to_csv(gdrive_url_out+file_out+'.csv', index=True)

标签: pythonloops

解决方案


推荐阅读