카테고리 없음

데이터프레임 합치기(concat함수)

히니1008 2022. 6. 16. 21:55

1.데이터 프레임 붙이기: pd.concat (  )

pd.concat( )함수는 데이터 프레임을 물리적으로 이어 붙여주는 함수. pd.concat(데이터프레임리스트)로 사용

df1 = pd.DataFrame({'a':['a0','a1','a2','a3'],
                   'b':['b0','b1','b2','b3'],
                   'c':['c0','c1','c2','c3']},
                  index = [0,1,2,3])

df2 = pd.DataFrame({'a':['a2','a3','a4','a5'],
                   'b':['b2','b3','b4','b5'],
                   'c':['c2','c3','c4','c5'],
                   'd':['d2','d3','d4','d5']},
                   index = [2,3,4,5])

print(df1, '\n')
print(df2)

#df1 데이터와 df2데이터 합치기

result1 = pd.concat([ df1, df2 ])
print(result1)

default 값으로 axis = 0 이 적용되기 때문에 행방향(위아래)로 데이터프레임을 이어붙임

-그냥 이어붙이면 ignore_index = True 를 주기 때문에 인덱스를 재배열 할 수 있다.

 

result2 = pd.concat([df1,df2], ignore_index=True)
print(result2)

#열 데이터 합치기

result3 = pd.concat([df1,df2],axis=1)
print(result3)


result3_in = pd.concat([df1,df2],axis=1, join='inner')   #열방향(axis=1), 교집합(inner)
print(result3_in)

# outer는 합집합, inner는 교집합


2.시리즈를 데이터 프레임 붙이기

sr1 = pd.Series(['e0','e1','e2','e3'], name = 'e')
sr2 = pd.Series(['f0','f1','f2'], name = 'f' , index = [3,4,5])
sr3 = pd.Sereis(['g0','g1','g2','g3'], name = 'g')
result4 = pd.concat([df1,sr1], axis=1)
print(result4, '\n')

result5 = pd.concat([df2,sr2], axis=1)
print(result5, '\n')


3.시리즈끼리 붙이기

result6 = pd.concat([sr1, sr3], axis = 1)  #열방향 연결, 데이터프레임
print(result6)
print(type(result6), '\n')

result7 = pd.concat([sr1, sr3], axis = 0)  #행방향 연결, 시리즈
print(result7)
print(type(result7), '\n')