2016-11-14 1 views
0

팬더기능 내가 팬더 dataframe이 테스트 테이블이 DF

Leaf_category_id session_id product_id 
0    111   1   987 
3    111   4   987 
4    111   1   741 
1    222   2   654 
2    333   3   321 

enter image description here

내가 원하는 결과가 있어야한다

for leaf_category_id 111: 

입니다.

session_id product_id 
1   987,741 
4   987 

은 마찬가지로 내가 모든 leaf_category 아이디의에 대해 동일한 수행하는 기능을 정의 할 수 있습니다, 내 테이블 행을 포함, 그것은 단지 스냅 샷이었다.

답변

1

당신은 join을 적용 boolean indexing 처음 사용과 다음 groupby 수 : 코멘트에 의해

df = pd.DataFrame({'Leaf_category_id':[111,111,111,222,333], 
        'session_id':[1,4,1,2,3], 
        'product_id':[987,987,741,654,321]}, 
        columns =['Leaf_category_id','session_id','product_id']) 

print (df)     
    Leaf_category_id session_id product_id 
0    111   1   987 
1    111   4   987 
2    111   1   741 
3    222   2   654 
4    333   3   321 


print (df[df.Leaf_category_id == 111] 
      .groupby('session_id')['product_id'] 
      .apply(lambda x: ','.join(x.astype(str)))) 
session_id 
1 987,741 
4  987 
Name: product_id, dtype: object 

편집 :

print (df.groupby(['Leaf_category_id','session_id'])['product_id'] 
     .apply(lambda x: ','.join(x.astype(str))) 
     .reset_index()) 
    Leaf_category_id session_id product_id 
0    111   1 987,741 
1    111   4  987 
2    222   2  654 
3    333   3  321 

또는 경우는 Leaf_category_idDataFrame에서 각각의 고유 값에 대한 필요 :

for i in df.Leaf_category_id.unique(): 
    print (df[df.Leaf_category_id == i] \ 
       .groupby('session_id')['product_id'] \ 
       .apply(lambda x: ','.join(x.astype(str))) \ 
       .reset_index()) 

    session_id product_id 
0   1 987,741 
1   4  987 
    session_id product_id 
0   2  654 
    session_id product_id 
0   3  321 
+0

마찬가지로 나는 정의 할 수있다. e 모든 leaf_category id에 대해 동일한 기능을 수행하는 함수 – Shubham

+0

오류 발생 ** TypeError : 시퀀스 항목 0 : 예상 문자열 numpy.int64가 발견됨 ** – Shubham

+0

df.dtypes 란 무엇입니까? – jezrael

관련 문제