【发布时间】:2015-09-27 16:04:07
【问题描述】:
我正在尝试合并两个程序或编写第三个程序,将这两个程序作为函数调用。它们应该一个接一个地运行,并在以分钟为单位的一定时间间隔后运行。类似于 make 文件,稍后将包含更多程序。我无法合并它们,也无法将它们放入某种格式,以便我可以在新的main 程序中调用它们。
program_master_id.py 从文件夹位置选择*.csv 文件,计算后将master_ids.csv 文件附加到文件夹的另一个位置。
Program_master_count.py 将count 与相应timeseries 中Ids 的计数相除。
Program_1 master_id.py
import pandas as pd
import numpy as np
# csv file contents
# Need to change to path as the Transition_Data has several *.CSV files
csv_file1 = 'Transition_Data/Test_1.csv'
csv_file2 = '/Transition_Data/Test_2.csv'
#master file to be appended only
master_csv_file = 'Data_repository/master_lac_Test.csv'
csv_file_all = [csv_file1, csv_file2]
# read csv into df using list comprehension
# I use buffer here, replace stringIO with your file path
df_all = [pd.read_csv(csv_file) for csv_file in csv_file_all]
# processing
# =====================================================
# concat along axis=0, outer join on axis=1
merged = pd.concat(df_all, axis=0, ignore_index=True, join='outer').set_index('Ids')
# custom function to handle/merge duplicates on Ids (axis=0)
def apply_func(group):
return group.fillna(method='ffill').iloc[-1]
# remove Ids duplicates
merged_unique = merged.groupby(level='Ids').apply(apply_func)
# do the subtraction
df_master = pd.read_csv(master_csv_file, index_col=['Ids']).sort_index()
# select matching records and horizontal concat
df_matched = pd.concat([df_master,merged_unique.reindex(df_master.index)], axis=1)
# use broadcasting
df_matched.iloc[:, 1:] = df_matched.iloc[:, 1:].sub(df_matched.iloc[:, 0], axis=0)
print(df_matched)
Program_2 master_count.py#This does not give any error nor gives any output.
import pandas as pd
import numpy as np
csv_file1 = '/Data_repository/master_lac_Test.csv'
csv_file2 = '/Data_repository/lat_lon_master.csv'
df1 = pd.read_csv(csv_file1).set_index('Ids')
# need to sort index in file 2
df2 = pd.read_csv(csv_file2).set_index('Ids').sort_index()
# df1 and df2 has a duplicated column 00:00:00, use df1 without 1st column
temp = df2.join(df1.iloc[:, 1:])
# do the division by number of occurence of each Ids
# and add column 00:00:00
def my_func(group):
num_obs = len(group)
# process with column name after 00:30:00 (inclusive)
group.iloc[:,4:] = (group.iloc[:,4:]/num_obs).add(group.iloc[:,3], axis=0)
return group
result = temp.groupby(level='Ids').apply(my_func)
我正在尝试编写一个main 程序,该程序将首先调用master_ids.py,然后调用master_count.py。它们是一种将两者合并到一个程序中还是将它们编写为函数并在新程序中调用这些函数的方法?请建议。
【问题讨论】:
-
这将有助于缩短这个例子,这样它会更快更容易阅读......但我认为你有 2 个基本选项。 (1) 将每一个封装在一个函数中,然后使用
time模块中的sleep()每隔5 分钟调用第二个函数,或者(2) 使用shell 脚本(例如linux 下的bash)分别调用每个程序并控制多久打电话一次。这可能是更好的方法,但取决于您的平台(mac/win/unix)和脚本语言的选择。 -
@JohnE 我将在 AWS EC2 的 Debian 实例上执行它们
-
嗯,这对我来说根本不是专业领域,所以我帮不上什么忙。您可能希望将此问题重新发布为带有“bash”的问题以及任何与 AWS 相关的适当标签。虽然如果你这样做,我会编辑问题以尽可能简化 python 部分。