데이터 프레임을 어떻게 피벗할 수 있나요?
피벗이란 무엇인가요?
피벗은 행과 열을 교환하여 DataFrame의 모양을 변경하는 데 사용되는 데이터 변환 기술입니다. 일반적으로 데이터를 더 쉽게 분석하거나 시각화할 수 있는 방식으로 구성하는 데 사용됩니다.
어떻게 피벗하나요?
DataFrame을 피벗하는 방법에는 여러 가지가 있습니다. Pandas 라이브러리를 사용하는 Python:
1. pd.DataFrame.pivot_table:
이 방법은 데이터 피벗을 위한 다양하고 기능이 풍부한 옵션입니다. 집계할 값, 집계 함수, 행 및 열 인덱스를 지정할 수 있습니다.
예:
import pandas as pd # Create a sample DataFrame df = pd.DataFrame({ "row": ["row0", "row1", "row2", "row3", "row4"], "col": ["col0", "col1", "col2", "col3", "col4"], "val0": [0.81, 0.44, 0.77, 0.15, 0.81], "val1": [0.04, 0.07, 0.01, 0.59, 0.64] }) # Pivot the DataFrame using pivot_table df_pivoted = df.pivot_table( index="row", columns="col", values="val0", aggfunc="mean", ) print(df_pivoted) # Output: col0 col1 col2 col3 col4 row row0 0.77 0.445 0.000 0.860 0.650 row1 0.130 0.000 0.395 0.500 0.250 row2 0.000 0.310 0.000 0.545 0.000 row3 0.000 0.100 0.395 0.760 0.240 row4 0.000 0.000 0.000 0.000 0.000
2. pd.DataFrame.groupby pd.DataFrame.unstack:
이 방법에는 DataFrame을 원하는 행 및 열 인덱스로 그룹화한 다음 unstack을 사용하여 그룹화된 데이터를 피벗하는 작업이 포함됩니다.
예:
# Group the DataFrame by row and col df_grouped = df.groupby(["row", "col"]) # Perform pivot using unstack df_pivoted = df_grouped["val0"].unstack(fill_value=0) print(df_pivoted) # Output: col col0 col1 col2 col3 col4 row row0 0.81 0.445 0.000 0.860 0.650 row1 0.130 0.000 0.395 0.500 0.250 row2 0.000 0.310 0.000 0.545 0.000 row3 0.000 0.100 0.395 0.760 0.240 row4 0.000 0.000 0.000 0.000 0.000
3. pd.DataFrame.set_index pd.DataFrame.unstack:
이 방법에는 원하는 행 및 열 인덱스를 DataFrame의 인덱스로 설정한 다음 unstack을 사용하여 데이터를 피벗하는 작업이 포함됩니다.
예:
# Set the row and col as the DataFrame's index df = df.set_index(["row", "col"]) # Perform pivot using unstack df_pivoted = df["val0"].unstack(fill_value=0) print(df_pivoted) # Output: col col0 col1 col2 col3 col4 row row0 0.81 0.445 0.000 0.860 0.650 row1 0.130 0.000 0.395 0.500 0.250 row2 0.000 0.310 0.000 0.545 0.000 row3 0.000 0.100 0.395 0.760 0.240 row4 0.000 0.000 0.000 0.000 0.000
4. pd.DataFrame.pivot:
이 방법은ivot_table에 비해 더 간단한 구문을 제공하지만 기능이 제한되어 있습니다. 행 및 열 인덱스만 지정할 수 있으며 집계는 수행할 수 없습니다.
예:
# Perform pivot using pivot df_pivoted = df.pivot(index="row", columns="col") print(df_pivoted) # Output: col col0 col1 col2 col3 col4 row row0 key0 0.81 0.44 0.00 0.86 0.65 row1 key1 0.13 0.00 0.39 0.50 0.25 row2 key1 0.00 0.31 0.00 0.54 0.00 row3 key0 0.00 0.10 0.39 0.76 0.24 row4 key1 0.00 0.00 0.00 0.00 0.00
긴 형식에서 와이드 형식으로
두 가지만 사용하여 DataFrame을 긴 형식에서 와이드 형식으로 변환하려면 열:
1. pd.DataFrame.pivot(index=column_to_index, columns=column_to_columns, value=values_to_pivot**):
예:
df["Combined"] = df["row"] + "|" + df["col"] df_pivoted = df.pivot(index="Combined", columns="A", values="B") print(df_pivoted) # Output: A a b c Combined row0|col0 0.0 10.0 7.0 row1|col1 11.0 10.0 NaN row2|col2 2.0 14.0 NaN row3|col3 11.0 NaN NaN row4|col4 NaN NaN NaN
2. pd.DataFrame.groupby pd.DataFrame.unstack:
df["Combined"] = df["row"] + "|" + df["col"] df_grouped = df.groupby(["Combined", "A"]) df_pivoted = df_grouped["B"].unstack(fill_value=0) print(df_pivoted) # Output: A a b c Combined row0|col0 0.0 10.0 7.0 row1|col1 11.0 10.0 NaN row2|col2 2.0 14.0 NaN row3|col3 11.0 NaN NaN row4|col4 NaN NaN NaN
피벗 후 여러 인덱스를 단일 인덱스로 평면화:
df_pivoted.columns = df_pivoted.columns.map("|".join) print(df_pivoted) # Output: a|col0 b|col0 c|col0 a|col1 b|col1 c|col1 a|col2 b|col2 c|col2 a|col3 b|col3 c|col3 row row0 0.0 10.0 7.0 11.0 10.0 NaN 2.0 14.0 NaN 11.0 NaN NaN row1 0.0 10.0 7.0 11.0 10.0 NaN 2.0 14.0 NaN 11.0 NaN NaN
위 내용은 Python에서 Pandas DataFrame을 어떻게 피벗할 수 있나요?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

PythonlistsCanstoreAnyDatAtype, ArrayModuLearRaysStoreOneType 및 NUMPYARRAYSAREFORNUMERICALPUTATION.1) LISTSAREVERSATILEBUTLESSMEMORY-EFFICENT.2) ARRAYMODUERRAYRAYRAYSARRYSARESARESARESARESARESARESAREDOREDORY-UNFICEDONOUNEOUSDATA.3) NumpyArraysUraysOrcepperperperperperperperperperperperperperperperferperferperferferpercient

whenyouattempttoreavalueofthewrongdatatypeinapythonaphonarray, thisiSdueTotheArrayModule의 stricttyPeenforcement, theAllElementStobeofthesAmetypecified bythetypecode.forperformancersassion, arraysaremoreficats the thraysaremoreficats thetheperfication the thraysaremorefications는

Pythonlistsarepartoftsandardlardlibrary, whileraysarenot.listsarebuilt-in, 다재다능하고, 수집 할 수있는 반면, arraysarreprovidedByTearRaymoduledlesscommonlyusedDuetolimitedFunctionality.

thescriptIsrunningwithHongpyThonversionDueCorRectDefaultTerpretersEttings.tofixThis : 1) checktheDefaultPyThonVersionUsingPyThon-VersionorPyThon3- version.2) usvirtual-ErondmentsBythePython.9-Mvenvmyenv, 활성화, 및 파괴

PythonArraysSupportVariousOperations : 1) SlicingExtractsSubsets, 2) 추가/확장 어드먼트, 3) 삽입 값 삽입 ATSpecificPositions, 4) retingdeletesElements, 5) 분류/ReversingChangesOrder 및 6) ListsompectionScreateNewListSbasedOnsistin

NumpyArraysareSentialplosplicationSefficationSefficientNumericalcomputationsanddatamanipulation. Theyarcrucialindatascience, MachineLearning, Physics, Engineering 및 Financeduetotheiribility에 대한 handlarge-scaledataefficivally. forexample, Infinancialanyaly

UseanArray.ArrayOveralistInpyThonWhendealingwithhomogeneousData, Performance-CriticalCode, OrinterFacingwithCcode.1) HomogeneousData : ArraysSaveMemorywithtypepletement.2) Performance-CriticalCode : arraysofferbetterporcomanceFornumericalOperations.3) Interf

아니요, NOTALLLISTOPERATIONARESUPPORTEDBYARRARES, andVICEVERSA.1) ArraySDONOTSUPPORTDYNAMICOPERATIONSLIKEPENDORINSERTWITHUTRESIGING, WHITHIMPACTSPERFORMANCE.2) ListSDONOTEECONSTANTTIMECOMPLEXITEFORDITITICCESSLIKEARRAYSDO.


핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

Video Face Swap
완전히 무료인 AI 얼굴 교환 도구를 사용하여 모든 비디오의 얼굴을 쉽게 바꾸세요!

인기 기사

뜨거운 도구

Atom Editor Mac 버전 다운로드
가장 인기 있는 오픈 소스 편집기

맨티스BT
Mantis는 제품 결함 추적을 돕기 위해 설계된 배포하기 쉬운 웹 기반 결함 추적 도구입니다. PHP, MySQL 및 웹 서버가 필요합니다. 데모 및 호스팅 서비스를 확인해 보세요.

DVWA
DVWA(Damn Vulnerable Web App)는 매우 취약한 PHP/MySQL 웹 애플리케이션입니다. 주요 목표는 보안 전문가가 법적 환경에서 자신의 기술과 도구를 테스트하고, 웹 개발자가 웹 응용 프로그램 보안 프로세스를 더 잘 이해할 수 있도록 돕고, 교사/학생이 교실 환경 웹 응용 프로그램에서 가르치고 배울 수 있도록 돕는 것입니다. 보안. DVWA의 목표는 다양한 난이도의 간단하고 간단한 인터페이스를 통해 가장 일반적인 웹 취약점 중 일부를 연습하는 것입니다. 이 소프트웨어는

WebStorm Mac 버전
유용한 JavaScript 개발 도구

Eclipse용 SAP NetWeaver 서버 어댑터
Eclipse를 SAP NetWeaver 애플리케이션 서버와 통합합니다.
