也许是一个简单的问题 - 查看下面的代码如何重新编写下面提供的示例以避免重复发生?
输入是pandas数据帧,它们在同一列名下包含不同的值 - 基本上是来自不同观察者的同一事件的测量值。我想减少这个函数的长度(以及其他我有类似重复的东西 - 不提供)。
这看起来就像是使用for循环的那种地方但是我不确定如何/如果我可以实现它来迭代函数输入?我希望这是一个简单的答案,但我还没有能够有效地定位我的谷歌搜索,以便自己揭示答案。希望你能帮忙!
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']
答案 0 :(得分:1)
将一个字典传递给该函数,然后为每个字典调用一次:
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)