다음 df가있는 경우 A 열로 그룹화하고 D 열을 각 A의 최대 D로 나누고 싶습니다.
df = pd.DataFrame({'A' : ['foo', 'bar', 'foo', 'bar',
...: ...: 'foo', 'bar', 'foo', 'foo'],
...: ...: 'B' : ['one', 'one', 'two', 'three',
...: ...: 'two', 'two', 'one', 'three'],
...: ...: 'C' : np.random.randn(8),
...: ...: 'D' : np.random.randn(8)})
나는 같은 것을 시도했다
max_by_id = df.groupby('A')['D'].max()
df = df.set_index('A')
df['D'] /= max_by_id.reset_index()['D']
하지만 이것은 나에게
ValueError: cannot reindex from a duplicate axis
온 집계에서 계산 된 최대 groupby
객체가 응집하여 원래 DF 열을 분할 할 경우 다음 호출 할 수있다, 따라서 에러가 감소 된 인덱스가 transform
온 groupby
목적이므로 인덱스 정렬한다 :
In [192]:
df['D'].div(df.groupby('A')['D'].transform('max'))
Out[192]:
0 -0.601098
1 -0.553823
2 -0.408006
3 1.000000
4 0.312029
5 0.709397
6 1.000000
7 0.140932
Name: D, dtype: float64
차이점을 확인할 수 있습니다.
In [193]:
df.groupby('A')['D'].transform('max')
Out[193]:
0 1.508660
1 1.378085
2 1.508660
3 1.378085
4 1.508660
5 1.378085
6 1.508660
7 1.508660
Name: D, dtype: float64
In [194]:
df.groupby('A')['D'].max()
Out[194]:
A
bar 1.378085
foo 1.508660
Name: D, dtype: float64
또한 reset_index
원래 grouped
열 레이블을 제거하는 경우 :
In [198]:
max_by_id.reset_index()['D']
Out[198]:
0 0.215997
1 0.962928
Name: D, dtype: float64
그러나 그 전에 인덱스를 'A'열로 설정했지만 실패합니다.
df['D'] /= max_by_id.reset_index()['D']
또한 lambda
with apply
를 사용 하여 동일한 작업을 수행 할 수 있습니다 lambda
.
df.groupby('A')['D'].apply(lambda x: x.div(x.max()))
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다