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

Python Pandas DataFrame에 리스트를 행으로 추가하는 방법

Python의 Pandas 라이브러리에서 리스트 데이터를 DataFrame에 새로운 행으로 추가하려면 append() 메서드를 사용할 수 있으며, loc() 메서드를 활용하는 방법도 있습니다. 이 글에서는 두 가지 방법을 예제와 함께 자세히 살펴보겠습니다.

기본 준비: 라이브러리 임포트 및 데이터 생성

먼저 필요한 라이브러리를 임포트합니다.

import pandas as pd

다음은 팀 순위 데이터를 리스트 형태로 준비한 것입니다.

Team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75], ['New Zealand', 4, 65], ['South Africa', 5, 50]]

위 데이터를 바탕으로 DataFrame을 생성하고 컬럼명을 지정합니다.

dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

방법 1: append() 메서드로 행 추가하기

추가할 행을 리스트로 준비합니다.

myList = [["Sri Lanka", 6, 40]]

위 리스트를 새로운 DataFrame으로 만든 후 기존 DataFrame에 연결(append)합니다.

dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)

참고: append() 메서드는 Pandas 1.4 버전부터 지원 중단(deprecated)되었으며, 2.0 버전부터는 완전히 제거되었습니다. 최신 버전에서는 아래와 같이 pd.concat()을 사용하는 것이 권장됩니다.

dataFrame = pd.concat([dataFrame, pd.DataFrame(myList, columns=['Country', 'Rank', 'Points'])], ignore_index=True)

예제 코드

다음은 append()를 사용하여 행을 추가하는 전체 코드입니다.

import pandas as pd

# 팀 순위 데이터 (리스트 형태)
Team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75], ['New Zealand', 4, 65], ['South Africa', 5, 50]]

# DataFrame 생성 및 컬럼 추가
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print("DataFrame...\n", dataFrame)

# 추가할 행
myList = [["Sri Lanka", 6, 40]]

# 리스트 형태의 행을 DataFrame에 추가
dataFrame = dataFrame.append(pd.DataFrame(myList, columns=['Country', 'Rank', 'Points']), ignore_index=True)

# 업데이트된 DataFrame 출력
print("\n행 추가 후 업데이트된 DataFrame...\n", dataFrame)

실행 결과

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

DataFrame...
         Country   Rank   Points
0         India      1      100
1     Australia      2       85
2      England      3       75
3  New Zealand      4       65
4 South Africa      5       50

행 추가 후 업데이트된 DataFrame...
         Country   Rank   Points
0         India      1      100
1     Australia      2       85
2      England      3       75
3  New Zealand      4       65
4 South Africa      5       50
5    Sri Lanka      6       40

방법 2: loc() 메서드로 행 추가하기

loc() 메서드를 사용하면 별도의 DataFrame 변환 없이 리스트를 직접 새로운 행으로 삽입할 수 있습니다. len(dataFrame)을 인덱스로 지정하면 항상 마지막 행 뒤에 데이터가 추가됩니다.

예제 코드

다음은 loc() 메서드를 사용하여 행을 추가하는 전체 코드입니다.

import pandas as pd

# 팀 순위 데이터 (리스트 형태)
Team = [['India', 1, 100], ['Australia', 2, 85], ['England', 3, 75], ['New Zealand', 4, 65], ['South Africa', 5, 50], ['Bangladesh', 6, 40]]

# DataFrame 생성 및 컬럼 추가
dataFrame = pd.DataFrame(Team, columns=['Country', 'Rank', 'Points'])

print("DataFrame...\n", dataFrame)

# 추가할 행
myList = ["Sri Lanka", 7, 30]

# loc()을 사용하여 리스트 형태의 행 추가
dataFrame.loc[len(dataFrame)] = myList

# 업데이트된 DataFrame 출력
print("\nloc()으로 행 추가 후 업데이트된 DataFrame...\n", dataFrame)

실행 결과

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

DataFrame...
         Country   Rank   Points
0         India      1      100
1     Australia      2       85
2      England      3       75
3  New Zealand      4       65
4 South Africa      5       50
5   Bangladesh      6       40

loc()으로 행 추가 후 업데이트된 DataFrame...
         Country   Rank   Points
0         India      1      100
1     Australia      2       85
2      England      3       75
3  New Zealand      4       65
4 South Africa      5       50
5   Bangladesh      6       40
6    Sri Lanka      7       30

정리

  • append(): 새 리스트를 DataFrame으로 변환한 뒤 기존 DataFrame에 연결하는 방식입니다. 단, 최신 Pandas 버전에서는 제거되었으므로 pd.concat() 사용을 권장합니다.
  • loc(): len(dataFrame)을 인덱스로 활용해 리스트를 마지막 행에 직접 할당하는 간단한 방식입니다.

두 방법 모두 ignore_index=True(또는 인덱스 재할당)를 통해 인덱스가 자동으로 정렬되므로, 반복적으로 행을 추가할 때 유용하게 활용할 수 있습니다.