Pandas: 두 열의 고유한 조합을 계산하는 방법
다음 구문을 사용하여 Pandas DataFrame의 두 열에 걸쳐 고유한 조합 수를 계산할 수 있습니다.
df[[' col1 ', ' col2 ']]. value_counts (). reset_index (name=' count ')
다음 예에서는 실제로 이 구문을 사용하는 방법을 보여줍니다.
예: Pandas에서 두 열의 고유한 조합 계산
다양한 농구 선수의 팀 과 위치를 보여주는 다음과 같은 팬더 DataFrame이 있다고 가정합니다.
import pandas as pd #create dataFrame df = pd. DataFrame ({' team ': ['Mavs', 'Mavs', 'Mavs', 'Mavs', 'Heat', 'Heat', 'Heat', 'Heat'], ' position ': ['Guard', 'Guard', 'Guard', 'Forward', 'Guard', 'Forward', 'Forward', 'Guard']}) #view DataFrame df team position 0 Mavs Guard 1 Mavs Guard 2 Mavs Guard 3 Mavs Forward 4 Heat Guard 5 Heat Forward 6 Heat Forward 7 Heat Guard
다음 구문을 사용하여 고유한 팀 및 위치 조합의 수를 계산할 수 있습니다.
df[[' team ', ' position ']]. value_counts (). reset_index (name=' count ') team position count 0 Mavs Guard 3 1 Heat Forward 2 2 Heat Guard 2 3 Mavs Forward 1
결과에서 우리는 다음을 볼 수 있습니다:
- Mavs-Guard 조합은 3번 발생합니다.
- Heat-Forward 조합이 2번 발생합니다.
- 히트가드 조합이 2번 발생합니다.
- Mavs-Forward 조합이 1번 발생합니다.
결과를 오름차순이나 내림차순으로 정렬할 수도 있습니다.
예를 들어, 다음 코드를 사용하여 결과를 숫자의 오름차순 으로 정렬할 수 있습니다.
df[[' team ', ' position ']]. value_counts (ascending= True ). reset_index (name=' count ') team position count 0 Mavs Forward 1 1 Heat Forward 2 2 Heat Guard 2 3 Mavs Guard 3
이제 결과가 숫자를 기준으로 가장 작은 것부터 가장 큰 것 순으로 정렬됩니다.
참고 : 여기에서 pandas value_counts() 함수에 대한 전체 문서를 찾을 수 있습니다.
추가 리소스
다음 튜토리얼에서는 Pandas에서 다른 일반적인 작업을 수행하는 방법을 설명합니다.
Pandas: GroupBy 및 값 개수를 사용하는 방법
Pandas: Bin 개수와 함께 GroupBy를 사용하는 방법
Pandas: 값 개수가 포함된 피벗 테이블을 만드는 방법