2016-12-20 3 views
3

여러 조건을 감안할 때 3 cols).팬더 계산 합계 (최대 10 명)을 다음과 같이 나는 형식으로 넓은 테이블이

여기서 유형은 4-7의 범위 일 수 있습니다. 여기서 값은 유형에 따라 값을 지정하는 다른 테이블에 해당합니다. 점에서 (

  1. A는 각 사람의 유형의 값의 입니다 : 그럼
    Type | Value 
    4 | 10 
    5 | 20 
    6 | 30 
    7 | 40 
    

    나는 두 개의 열, 'A'와 'B'를 계산해야 상태 = 0
  2. B)이 그 행에서 (여기서 상태 = 1
01 각자의 유형의 값의 합 인 행) 예를 들어 23,516,

는 결과 열 'A'및 'B'는 것이 다음과 같이

A | B 
70 | 10 

이에 대한 설명 :

PERSON1 및 person3이 때문에 'A'는 값 70를 갖는다 "상태 "0이고 7과 6의 해당 유형이 있습니다 (값 30과 40에 해당).

마찬가지로 person2 만 상태가 "1"이고 유형이 "4"(해당 값이 10)이기 때문에 "10"값을 갖는 다른 열 'B'가 있어야합니다.

이것은 아마도 바보 같은 질문 일 수 있습니다. 그러나 이것을 어떻게 벡터화 된 방식으로 수행합니까? for 루프 나 다른 것을 사용하고 싶지 않습니다. 효율성이 떨어질 것이기 때문에 ...

나는 누군가가 나를 도울 수 있었으면 좋겠습니까? 나는 이것을 알아 내려고 뇌사라고 생각한다.

단순한 계산 된 열에 대해서는 np.where 만 사용하고 있었지만 별도의 테이블에서 해당 값을 가져 오는 동안 특정 조건이 지정된 여러 열의 값의 합계를 계산해야하기 때문에 여기에 조금 붙어 있습니다. ... 의미

+1

[최소, 완료 및 확인 가능한 예제] (http://stackoverflow.com/help/mcve)를 제공 할 수 있습니까? –

+0

내가 더 명확하게 준 예입니다 – shishy

답변

1

사용하는 문자열이 그들에 표시되는 위치를 사람들을 위해 열 이름을 필터링합니다 필터 방법을 만들어

희망.

조회 값 other_table에 대한 데이터 프레임을 만들고 인덱스를 유형 열로 설정하십시오.

df_status = df.filter(like = 'status') 
df_type = df.filter(like = 'type') 
df_type_lookup = df_type.applymap(lambda x: other_table.loc[x]).values 

df['A'] = np.sum((df_status == 0).values * df_type_lookup, 1) 
df['B'] = np.sum((df_status == 1).values * df_type_lookup, 1) 
아래

전체 예 :

만들기 가짜 데이터

df = pd.DataFrame({'person_1_status':np.random.randint(0, 2,1000) , 
        'person_2_status':np.random.randint(0, 2,1000), 
        'person_3_status':np.random.randint(0, 2,1000), 
        'person_1_type':np.random.randint(4, 8,1000), 
        'person_2_type':np.random.randint(4, 8,1000), 
        'person_3_type':np.random.randint(4, 8,1000)}, 
       columns= ['person_1_status', 'person_2_status', 'person_3_status', 
          'person_1_type', 'person_2_type', 'person_3_type']) 

person_1_status person_2_status person_3_status person_1_type \ 
0    1    0    0    7 
1    0    1    0    6 
2    1    0    1    7 
3    0    0    0    7 
4    0    0    1    4 

    person_3_type person_3_type 
0    5    5 
1    7    7 
2    7    7 
3    7    7 
4    7    7 

other_table

other_table = pd.Series({4:10, 5:20, 6:30, 7:40}) 

4 10 
5 20 
6 30 
7 40 
dtype: int64 

상태를 필터링하고 자신의 dataframes에 열을 입력하십시오

백79경1천1백10조8천9백74억8천1백72만3천2백10

메이크 룩업 테이블

df_type_lookup = df_type.applymap(lambda x: other_table.loc[x]).values 

행에 걸쳐 매트릭스 곱셈 및 합계를 적용한다.

df['A'] = np.sum((df_status == 0).values * df_type_lookup, 1) 
df['B'] = np.sum((df_status == 1).values * df_type_lookup, 1) 

는 출력

person_1_status person_2_status person_3_status person_1_type \ 
0    0    0    1    7 
1    0    1    0    4 
2    0    1    1    7 
3    0    1    0    6 
4    0    0    1    5 

    person_2_type person_3_type A B 
0    7    5 80 20 
1    6    4 20 30 
2    5    5 40 40 
3    6    4 40 30 
4    7    5 60 20 
+0

정확히 내가 원했던 것, 감사합니다! 나는 필터 명령에 대해 몰랐고 ... 그 람다 함수가 더 쉽게 만들었습니다. 매우 감사 :). – shishy

0

는 dataframe이 우리가 type == 1

이 작업을 수행 할 수 있습니다 구성되어 df

mux = pd.MultiIndex.from_product([['status', 'type'], ['p%i' % i for i in range(1, 6)]]) 
data = np.concatenate([np.random.choice((0, 1), (10, 5)), np.random.rand(10, 5)], axis=1) 
df = pd.DataFrame(data, columns=mux) 
df 

enter image description here

방법을 고려

df.status.mul(df.type).sum(1) 

0 0.935290 
1 1.252478 
2 1.354461 
3 1.399357 
4 2.102277 
5 1.589710 
6 0.434147 
7 2.553792 
8 1.205599 
9 1.022305 
dtype: float64 

와 (1)

0 1.867986 
1 1.068045 
2 0.653943 
3 2.239459 
4 0.214523 
5 0.734449 
6 1.291228 
7 0.614539 
8 0.849644 
9 1.109086 
dtype: float64 

당신이 당신의 열을 얻을 수 type == 0

df.status.rsub (1) .mul (df.type) .sum에 대한 3,691,363,210 다음 코드를 사용하여 형식을 지정하십시오.

df.columns = df.columns.str.split('_', expand=True) 
df = df.swaplevel(0, 1, 1)