Pandas dataframe에 행을 추가하는 방법(예제 포함)
df.loc() 함수를 사용하여 Pandas DataFrame 끝에 줄을 추가할 수 있습니다.
#add row to end of DataFrame df. loc [ len (df. index )] = [value1, value2, value3, ...]
그리고 df.append() 함수를 사용하여 기존 DataFrame의 여러 줄을 다른 DataFrame의 끝에 추가할 수 있습니다.
#append rows of df2 to end of existing DataFrame df = df. append (df2, ignore_index = True )
다음 예에서는 이러한 기능을 실제로 사용하는 방법을 보여줍니다.
예시 1: Pandas DataFrame에 행 추가
다음 코드는 Pandas DataFrame의 끝에 줄을 추가하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [10, 12, 12, 14, 13, 18], ' rebounds ': [7, 7, 8, 13, 7, 4], ' assists ': [11, 8, 10, 6, 6, 5]}) #view DataFrame df points rebound assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #add new row to end of DataFrame df. loc [ len (df. index )] = [20, 7, 5] #view updated DataFrame df points rebound assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 6 20 7 5
예 2: Pandas DataFrame에 여러 행 추가
다음 코드는 기존 DataFrame의 여러 줄을 다른 DataFrame의 끝에 추가하는 방법을 보여줍니다.
import pandas as pd #createDataFrame df = pd. DataFrame ({' points ': [10, 12, 12, 14, 13, 18], ' rebounds ': [7, 7, 8, 13, 7, 4], ' assists ': [11, 8, 10, 6, 6, 5]}) #view DataFrame df points rebound assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 #define second DataFrame df2 = pd. DataFrame ({' points ': [21, 25, 26], ' rebounds ': [7, 7, 13], ' assists ': [11, 3, 3]}) #add new row to end of DataFrame df = df. append (df2, ignore_index = True ) #view updated DataFrame df points rebound assists 0 10 7 11 1 12 7 8 2 12 8 10 3 14 13 6 4 13 7 6 5 18 4 5 6 21 7 11 7 25 7 3 8 26 13 3
한 DataFrame의 행을 다른 DataFrame의 끝에 성공적으로 추가하려면 두 DataFrame의 열 이름이 동일해야 합니다.
추가 리소스
Pandas DataFrame에 열을 추가하는 방법
Pandas DataFrame에서 행 번호를 얻는 방법
Pandas에서 목록을 인라인 DataFrame으로 변환하는 방법