python - 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)
解决方案
推荐阅读
- reactjs - Prisma Playground 中的 React + Apollo“入门”错误
- flutter - 如何 Flutter Webview 从 Web 重定向到 StatelessWidget?
- html - iframe 的高度/宽度
- css - 带有 Bootstrap 4 的顶部菜单下带有粘性资源的 FullCalendar 5
- open-liberty - 这个openliberty docker错误的原因是什么
- c - 如何获取切片的地址为 u64?
- r - 有没有办法通过 R 激活 Excel 加载项?
- reactjs - useSelector() 提供初始值而不是更新值?
- r - 在R中收集具有相同名称的长度不等的列
- javascript - 如何使用具有完全沉浸式模式的 Apache Cordova 构建 Android 应用程序(任何地方都没有 Android 条 - 电池、时间、..)?