오늘의 인기 글
최근 글
최근 댓글
Today
Total
05-19 08:40
관리 메뉴

우노

[Python] Pandas DataFrame 행 추가 본문

Language/Python

[Python] Pandas DataFrame 행 추가

운호(Noah) 2022. 2. 12. 00:11

들어가기 앞서,

  • DataFrame 은, ‘append’, ‘loc’, ‘iloc’ 를 사용해 행 데이터를 추가할 수 있습니다.

원본 DataFrame

import numpy as np
import pandas as pd

data = {'BatchSize':[1, 2],'Accuracy':[0.5, 0.6]}
df = pd.DataFrame(data,index=['First','Second'])
df

append

  • append 는, DataFrame 마지막 행에 데이터를 추가할 수 있습니다.

  • 하지만, 만약 추가하려는 데이터의 형식이 DataFrame 이 아닌, Dictionary, Series 일 경우,

  • 원본 DataFrame 의 index 형식이 파괴될 수 있습니다.

  • 예제 코드

      new_row = {'BatchSize' : 4, 'Accuracy' : 0.7}    
      df = df.append(new_row, ignore_index=True)       
      df

loc

  • loc 는, 데이터 삽입을 원하는 행의 index 명을 지정해 추가할 수 있습니다.

  • 원본 DataFrame 에 해당 index 명이 존재하는 경우에는, 해당 index 의 데이터가 업데이트 되며,

  • index 명이 존재하지 않는 경우에는, 새로운 index 로 데이터가 추가됩니다.

  • 예제 코드

      new_row = {'BatchSize' : 4, 'Accuracy' : 0.7}
      df.loc['Third'] = new_row
      df

iloc

  • iloc 는, 데이터 업데이트를 원하는 행의 index 번호를 지정해, 데이터를 업데이트할 수 있습니다.

  • 즉, 원본 DataFrame 에 해당 index 번호가 존재할 경우에만 업데이트가 가능합니다.

  • 예제 코드

      new_row = {'BatchSize' : 4, 'Accuracy' : 0.7}
      df.iloc[1] = new_row
      df

Comments