2016-11-07 3 views
0

아마도 간단한 질문입니다 - 아래 코드를 보면 중복이 발생하지 않도록 아래 제공된 샘플을 다시 작성할 수 있습니까?여러 함수 입력에서 동일한 작업 수행

입력은 동일한 열 이름 아래에서 다른 값을 포함하는 팬더 데이터 프레임입니다. 기본적으로 다른 관찰자의 동일한 이벤트를 측정합니다. 나는이 기능의 길이를 줄이기를 원한다.

이것은 for 루프를 사용하는 것과 같은 것으로 보이지만 어떻게 함수 입력을 통해 iterate하도록 구현할 수 있는지 모르겠습니다. 나는 이것이 직접적인 대답 일 것이라고 기대하지만 나는 내 자신의 대답을 효과적으로 보여주기 위해 내 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'] 
+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)