Computer >> 컴퓨터 >  >> 프로그래밍 >> Python

Python Pandas – DataFrame의 행과 열 개수 구하는 방법

Pandas에서 DataFrame의 행(row)과 열(column) 개수를 확인할 때는 shape 속성을 사용합니다. shape는 별도의 인자 없이 호출할 수 있으며, (행의 수, 열의 수) 형태의 튜플(tuple)을 반환해 데이터의 크기를 한눈에 파악할 수 있게 해줍니다.

이번 글에서는 실제 CSV 파일을 불러와 행과 열의 개수를 구하는 전체 과정을 예제와 함께 살펴보겠습니다.

1. 예제 파일 준비

먼저 아래 경로처럼 바탕화면(Desktop)에 CSV 파일이 저장되어 있다고 가정합니다.

C:\Users\amit_\Desktop\CarRecords.csv

2. CSV 파일 불러오기

pd.read_csv() 함수를 사용해 CSV 파일을 DataFrame으로 읽어옵니다.

import pandas as pd

dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")

3. shape 속성으로 행·열 개수 확인

DataFrame의 행과 열 개수는 다음 한 줄이면 충분합니다.

dataFrame.shape

전체 예제 코드

지금까지의 내용을 하나로 합친 전체 코드는 다음과 같습니다.

import pandas as pd

# CSV 파일 읽기
dataFrame = pd.read_csv("C:\\Users\\amit_\\Desktop\\CarRecords.csv")
print("DataFrame...\n", dataFrame)

# DataFrame의 행과 열 개수 세기
print("\nNumber of rows and columns in our DataFrame = ", dataFrame.shape)

# 상위 5개 행만 출력하기
print("\nDataFrame with specific number of rows...\n", dataFrame.head(5))

실행 결과

위 코드를 실행하면 다음과 같은 출력 결과를 얻을 수 있습니다.

DataFrame...
          Car       Place   UnitsSold
0         Audi   Bangalore          80
1      Porsche      Mumbai         110
2  RollsRoyce        Pune         100
3         BMW       Delhi          95
4    Mercedes   Hyderabad          80
5 Lamborghini  Chandigarh          80
6        Audi      Mumbai         100
7    Mercedes        Pune         120
8 Lamborghini       Delhi         100

Number of rows and columns in our DataFrame = (9, 3)

DataFrame with specific number of rows ...
         Car      Place  UnitsSold
0       Audi  Bangalore         80
1    Porsche     Mumbai        110
2 RollsRoyce       Pune        100
3        BMW      Delhi         95
4   Mercedes  Hyderabad         80

결과 해석

shape가 반환한 값은 (9, 3)입니다. 이는 해당 DataFrame에 총 9개의 행3개의 열(Car, Place, UnitsSold)이 있다는 의미입니다. 또한 head(5)를 사용하면 상위 5개 행만 따로 확인할 수 있어, 대용량 데이터를 빠르게 미리보기할 때 매우 유용합니다.

참고: len() 함수로 각각 구하기

shape 외에도 len() 함수를 활용하면 행과 열의 개수를 각각 구할 수 있습니다.

row_count = len(dataFrame)            # 또는 len(dataFrame.index)
col_count = len(dataFrame.columns)
print(row_count, col_count)           # 출력: 9 3