2016-09-28 11 views
1

그런 식으로 데이터 프레임 df을 감안할 때 :python-pandas에서 groupby와 배열을 열에 할당하는 방법은 무엇입니까?

a  b  
2  nan 
3  nan 
3  nan 
4  nan 
4  nan 
4  nan 
5  nan 
5  nan 
5  nan 
5  nan 
... 

중요한 규칙은 그 a 반복 n-1 행에 각 번호 n. 그리고 내 예상 출력은 다음과 같습니다

a  b  
2  1 
3  1 
3  2 
4  1 
4  2 
4  3 
5  1 
5  2 
5  3 
5  4 
... 

따라서 b의 숫자 m1에서 n-1에 대한 목록입니다. 나는이 방법으로 시도 :

df.groupby('a').apply(lambda x: np.asarray(range(x['a'].unique()[0]))) 

결과는 한 행에있는 목록이며, 이는 내가 원하는 것이 아닙니다.

구현 방법을 알려주시겠습니까? 미리 감사드립니다!

답변

3

당신은 cumcount이 필요합니다 : 당신의 좋은 답변

df['b'] = df.groupby('a').cumcount() + 1 
print (df) 
    a b 
0 2 1 
1 3 1 
2 3 2 
3 4 1 
4 4 2 
5 4 3 
6 5 1 
7 5 2 
8 5 3 
9 5 4 
1
# make a column that is 0 on the first occurrence of a number in a and 1 after 
df['is_duplicated'] = df.duplicated(['a']).astype(int) 

# group by values of a and get the cumulative sum of duplicates 
# add one since the first duplicate has a value of 0 
df['b'] = df[['a', 'is_duplicated']].groupby(['a']).cumsum() + 1 
+0

감사합니다! 훌륭한! –

관련 문제