2016-11-07 55 views
0

也許一個簡單的問題 - 查看下面的代碼如何重新編寫下面提供的示例以避免發生重複?對多個功能輸入執行相同的操作

輸入是熊貓數據框架,它們在同一列名稱下包含不同的值 - 基本上是來自不同觀察者的相同事件的測量結果。我想將這個函數的長度(和其他有類似重複的地方 - 不提供)縮短一半。

這看起來像使用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

只是傳遞一個字典的功能,以及(對於每個字典一次)調用該函數的兩倍。 –

+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)