对多个函数输入执行相同的操作

Performing same operation on multiple function inputs

也许是一个简单的问题 - 查看下面的代码,我如何重写下面提供的示例以避免正在发生的重复?

输入是 pandas 数据框,在同一列名称下包含不同的值 - 基本上是来自不同观察者的同一事件的测量值。我想将此函数(以及其他有类似重复的函数 - 未提供)的长度减半。

这看起来正是使用 for 循环的地方,但我不确定 how/if 我可以实现它来遍历函数输入吗?我希望这是一个直截了当的答案,但我无法有效地定位我的 google 搜索以自行揭示答案。希望你能帮上忙!

def data_manipulation(a, b):
"""
Performs math operations on the values contained in trajectory1(and 2). The raw values contained there are converted
to more useful forms: e.g. apparent to absolute magnitude. These new results are added to the pandas data frame.
Unnecessary data columns are deleted.

All equations/constants are lifted from read_data_JETS.

To Do:  -   remove code duplication where the same operation in written twice (once for each station).

:param a: Pandas Data Frame containing values from first station.
:param b: Pandas Data Frame containing values from second station.
:return:
"""

# Convert apparent magnitude ('Bright') to absolute magnitude (Abs_Mag).
a['Abs_Mag'] = (a['Bright'] + 2.5 *
                np.log10((100 ** 2) / ((a['dist'] / 1000) ** 2))) - 0.25
b['Abs_Mag'] = (b['Bright'] + 2.5 *
                np.log10((100 ** 2) / ((b['dist'] / 1000) ** 2))) - 0.25

# Calculate the error in absolute magnitude where 1 is the error in apparent magnitude and 0.001(km) is the error
# in distance ('dist').
a['Abs_Mag_Err'] = 1 + (5 / (a['dist'] / 1000) * 0.001)
b['Abs_Mag_Err'] = 1 + (5 / (b['dist'] / 1000) * 0.001)

# Calculate the meteor luminosity from absolute magnitude.
a['Luminosity'] = 525 * 10 ** (-0.4 * a['Abs_Mag'])
b['Luminosity'] = 525 * 10 ** (-0.4 * b['Abs_Mag'])

# Calculate the error in luminosity.
a['Luminosity_Err'] = abs(-0.4 * a['Luminosity'] * np.log(10) * a['Abs_Mag_Err'])
b['Luminosity_Err'] = abs(-0.4 * b['Luminosity'] * np.log(10) * b['Abs_Mag_Err'])

# Calculate the integrated luminosity of each meteor for both stations.
a['Intg_Luminosity'] = a['Luminosity'].sum() * 0.04
b['Intg_Luminosity'] = b['Luminosity'].sum() * 0.04

# Delete column containing apparent magnitude.
del a['Bright']
del b['Bright']

将一个字典传递给函数,然后为每个字典调用一次:

def data_manipulation(x):
    x['Abs_Mag'] = (x['Bright'] + 2.5 * np.log10((100 ** 2) / ((x['dist'] / 1000) ** 2))) - 0.25
    x['Abs_Mag_Err'] = 1 + (5 / (x['dist'] / 1000) * 0.001)
    x['Luminosity'] = 525 * 10 ** (-0.4 * x['Abs_Mag'])
    x['Luminosity_Err'] = abs(-0.4 * x['Luminosity'] * np.log(10) * x['Abs_Mag_Err'])
    x['Intg_Luminosity'] = x['Luminosity'].sum() * 0.04
    del x['Bright']

data_manipulation(a)
data_manipulation(b)