2016-08-23 2 views
0

팬더 문제에 갇혀 있었지만 그걸 알아낼 수 없습니다. 나는의 모든 후속 행에 대해 다음 new_column = no을 다음 의사 심판에서 각각의 고유 값에 대한팬더는 고유 한 값을 열에 적용합니다.

으로이 dataframe에 새 열을 추가 result = fail 경우 할

ref, value, rule, result, new_column 
a100, 25, high, fail, nan 
a100, 25, high, pass, nan 
a100, 25, medium, fail, nan 
a100, 25, medium, pass, nan 
a101, 15, high, fail, nan 
a101, 15, high, pass, nan 
a102, 20, high, pass, nan 

: 나는이 같은 dataframe이 같은 "ref"값.

새 데이터 프레임의 모습입니다.

ref, value, rule, result, new_column 
a100, 25, high, fail, no 
a100, 25, high, pass, yes 

이것은 df.loc 기능을 통해 이루어진다 : 내가 관리했습니다 무엇

ref, value, rule, result, new_column 
a100, 25, high, fail, no 
a100, 25, high, pass, no 
a100, 25, medium, fail, no 
a100, 25, medium, pass, no 
a101, 15, high, fail, no 
a101, 15, high, pass, no 
a102, 20, high, pass, yes 

는 다음과 같습니다. 하지만 각 행이 아닌 고유 한 값에 적용하는 함수가 필요합니다.

+0

당신이'NEW_COLUMN = no' 또는'yes' 생각하십니까? – jezrael

+1

데이터 프레임에 행을 더 추가 할 수 있습니까? 왜냐하면 제 생각에는 다소 불투명합니다. – jezrael

+0

@jezrael 업데이트를 확인하십시오. new_column = no는 각 고유 참조 값에 대해 result = fail 인 모든 인스턴스에 대해 적용됩니다. – Kvothe

답변

3

난 당신이 transform를 사용할 수 있다고 생각 :

print (df) 
    ref value rule result new_column 
0 a100  25 high pass   NaN 
1 a100  25 high fail   NaN 
2 a100  25 medium fail   NaN 
3 a100  25 medium pass   NaN 
4 a101  15 high fail   NaN 
5 a101  15 high pass   NaN 
6 a102  20 high pass   NaN 

df['new_column']=df.groupby('ref')['result'] 
        .transform(lambda x: 'no' if ((x=='fail').any()) else 'yes') 
print (df) 
    ref value rule result new_column 
0 a100  25 high pass   no 
1 a100  25 high fail   no 
2 a100  25 medium fail   no 
3 a100  25 medium pass   no 
4 a101  15 high fail   no 
5 a101  15 high pass   no 
6 a102  20 high pass  yes 

replace 또 다른 솔루션을 당신에게 Jon Clements 감사합니다

df['new_column'] = df.groupby('ref')['result'] 
        .transform(lambda L: (L == 'fail').any()) 
        .replace({True: 'no', False: 'yes'}) 

print (df) 
    ref value rule result new_column 
0 a100  25 high pass   no 
1 a100  25 high fail   no 
2 a100  25 medium fail   no 
3 a100  25 medium pass   no 
4 a101  15 high fail   no 
5 a101  15 high pass   no 
6 a102  20 high pass  yes 
+0

음 ... 나는 'df.groupby ('ref ') ['result '] 변형을 가지고있다 (lambda L : (L =='fail '). 거짓 : '예'})' –

+0

@ 존 클레멘트 - 감사합니다. – jezrael

+0

@jezrael 감사합니다. 이것은 정확히 내가 원했던 것입니다 :) – Kvothe

관련 문제