다음과 같은 DataFrame이있는 경우 :
type value group
a 10 one
b 45 one
a 224 two
b 119 two
a 33 three
b 44 three
이것을 어떻게 만들 수 있습니까?
type one two three
a 10 224 33
b 45 119 44
나는 그것이 될 것이라고 생각 pivot_table
했지만 그것은 다시 그룹화 된 목록을 제공합니다.
난 당신이 필요하다고 생각 pivot
과 함께 rename_axis
(새의 pandas
0.18.0
)과 reset_index
:
print df.pivot(index='type', columns='group', values='value')
.rename_axis(None, axis=1)
.reset_index()
type one three two
0 a 10 33 224
1 b 45 44 119
열 순서가 중요한 경우 :
df = df.pivot(index='type', columns='group', values='value').rename_axis(None, axis=1)
print df[['one','two','three']].reset_index()
type one two three
0 a 10 224 33
1 b 45 119 44
편집하다:
실제 데이터에서 오류가 발생할 수 있습니다.
print df.pivot(index='type', columns='group', values='value')
.rename_axis(None, axis=1)
.reset_index()
ValueError : 색인에 중복 된 항목이 포함되어있어 모양을 변경할 수 없습니다.
print df
type value group
0 a 10 one
1 a 20 one
2 b 45 one
3 a 224 two
4 b 119 two
5 a 33 three
6 b 44 three
문제는 두 번째 행에 - 당신은 인덱스 값을 얻을 수 a
및 열 one
두 값 - 10
와 20
. pivot_table
이 경우 함수 집계 데이터입니다. Dafault 집계 함수는 np.mean
이지만 매개 변수로 변경할 수 있습니다 aggfunc
.
print df.pivot_table(index='type', columns='group', values='value', aggfunc=np.mean)
.rename_axis(None, axis=1)
.reset_index()
type one three two
0 a 15 33 224
1 b 45 44 119
print df.pivot_table(index='type', columns='group', values='value', aggfunc='first')
.rename_axis(None, axis=1)
.reset_index()
type one three two
0 a 10 33 224
1 b 45 44 119
print df.pivot_table(index='type', columns='group', values='value', aggfunc=sum)
.rename_axis(None, axis=1)
.reset_index()
type one three two
0 a 30 33 224
1 b 45 44 119
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다