2017-11-19 6 views
0

다음 예제에서는 팬더 데이터 프레임의 값을 기준으로 조건부로 채워진 값으로 "지출"이라는 새 열을 어떻게 만들려고합니까? 다른 컬럼?팬더 : 함수 사전을 사용하여 다른 열 사이의 계산을 기반으로하는 열 값을 할당하는 방법

함수 사전을 사용하여 계산중인 메트릭을 기반으로 함수를 구성하고 싶습니다. 또한 계산은 다른 열의 데이터로 수행됩니다. 다른 데이터 열 이름은 일관성이 없으며 실행 중에 정의해야 할 수도 있습니다.

예 데이터 집합은

cost method metric rate total planned 
0  CPMV 2000 100   1000 
1  CPMV 4000 100   1000 
2  Flat  0  0   1000 
3  Flat  0  0    0 
4  Free  1  2    3 

나는 비용 방법에 따라 비용을 계산해야합니다. CPMV는 측정 항목을 1000으로 나눈 값과 비율을 곱할 필요가 있습니다. flight_length, 및 무료가 0 일 필요가있는 캠페인 길이 (2로 설정할 수 있음)를 나타내는 정적 변수로 평면을 "전체 계획"으로 나눠야합니다.

답변

1

먼저 계산에 사용할 필드 인수가있는 함수 사전을 설정하면됩니다. 그런 다음 적용 함수 내에서 람다를 사용하여 어떤 키의 기능을 사용할지 결정할 수 있습니다.

safe_div 함수를 사용하여 flight_length가 0이면 오류 대신 total_planned가 반환됩니다.

# make safe_div 
def safe_div(x,y): 
    if y == 0: 
     return x 
    return x/y 

# write the dictionary 
def applyCalculateSpend (df_name, cost_method_col, metric_col, rate_col, total_planned_col): 
    calculations = { 
      'CPMV' : df_name[metric_col]/1000 * df_name[rate_col], 
      'Flat' : safe_div(df_name[total_planned_col], flight_week_diff), 
      'Free' : 0 
      } 
    df_method = df_name[cost_method_col] 
    return calculations.get(df_method, "not in dict") 

# call the function inside a lambda 
test_df['spend'] = test_df.apply(lambda row: applyCalculateSpend(
row, 
cost_method_col='cost method', 
metric_col='metric', 
rate_col='rate', 
total_planned_col='total planned'), axis = 1) 

    cost method metric rate total planned spend 
0  CPMV 2000 100   1000 200.0 
1  CPMV 4000 100   1000 400.0 
2  Flat  0  0   1000 500.0 
3  Flat  0  0    0 0.0 
4  Free  1  2    3 0.0