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

Python Pandas에서 인덱스 없이 DataFrame 출력하는 방법

Pandas에서 DataFrame을 출력하면 기본적으로 왼쪽에 행 인덱스가 함께 표시됩니다. 인덱스를 숨기고 데이터만 깔끔하게 출력하려면 to_string() 메서드에 index=False 옵션을 지정하면 됩니다.

1. 필요한 라이브러리 가져오기

먼저 Pandas 라이브러리를 임포트합니다.

import pandas as pd

2. DataFrame 생성하기

사용자 지정 인덱스('x', 'y', 'z')와 컬럼('a', 'b')을 가진 DataFrame을 생성합니다.

dataFrame = pd.DataFrame(
    [[10, 15], [20, 25], [30, 35]],
    index=['x', 'y', 'z'],
    columns=['a', 'b']
)

3. loc를 사용해 특정 행 선택하기

라벨(label)을 전달하여 원하는 행을 선택할 수 있습니다.

dataFrame.loc['x']

4. 인덱스 없이 DataFrame 출력하기

to_string(index=False)를 호출하면 인덱스 열이 제거된 상태로 문자열이 반환되어 출력됩니다.

print(dataFrame.to_string(index=False))

전체 예제 코드

import pandas as pd

# DataFrame 생성
dataFrame = pd.DataFrame(
    [[10, 15], [20, 25], [30, 35]],
    index=['x', 'y', 'z'],
    columns=['a', 'b']
)

# 인덱스와 함께 DataFrame 출력
print("인덱스와 함께 DataFrame 출력...\n", dataFrame)

# loc로 라벨을 지정해 행 선택
print("\n라벨을 전달하여 행 선택...")
print(dataFrame.loc['x'])

# 인덱스 없이 DataFrame 출력
print("\n인덱스 없이 DataFrame 출력...\n", dataFrame.to_string(index=False))

실행 결과

위 코드를 실행하면 다음과 같은 결과가 출력됩니다.

인덱스와 함께 DataFrame 출력...
     a   b
x  10  15
y  20  25
z  30  35

라벨을 전달하여 행 선택...
a    10
b    15
Name: x, dtype: int64

인덱스 없이 DataFrame 출력...
 a   b
10  15
20  25
30  35

추가 팁

Jupyter Notebook 환경에서는 df.style.hide(axis='index')를 사용해도 동일한 효과를 얻을 수 있습니다. 또한 CSV 파일로 저장할 때도 to_csv(index=False)처럼 같은 옵션이 적용되므로, 불필요한 인덱스 컬럼이 파일에 포함되지 않도록 주의하는 것이 좋습니다.