pandas3

2020. 9. 10. 22:40Python

. read_csv()

: atom에서 쓸때 안될때가 있다. 

이때는 아래 블로그를 참고한다. 

https://eclipse360.tistory.com/4

 

[파이썬] SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 해결법

파이썬 pandas 모듈에서 파일을 불러올 때, import pandas as pd CCTV = pd.read_csv('C:\Users\CCTV.csv', encoding='utf-8') CCTV.head() 를 돌려보면 SyntaxError: (unicode error) 'unicodeescape' codec can..

eclipse360.tistory.com

 

데이터 프레임 붙이는 방법

1. concat() : 두 데이터 프레임을 위/아래 또는 왼쪽 오른쪽으로 연결하기만 함

axis = 1이 있으면 그냥 가로로 붙인다. 

없으면 세로로 붙임

# 1. data frame 합치기
print(pd.concat([data1, data2]))
print(pd.concat([data1, data2], axis = 1))

2. merge() : 두 데이터 프레임에 동일한 이름을 가진 컬럼을 기준으로 두 데이터 프레임을 합침

# 동일한 인덱스가 있는 컬럼들만 합쳐서 보여주고 안동일한 애들은 안보여줌
print(pd.merge(data1, data2))

# 예를 들어 생성한 id란 컬럼이 있는 경우 그러한 특정 컬럼을 기준으로 합치도록 한다. 
print(pd.merge(data1, data2, on = 'id'))

merge는 SQL과 유사하다. 

merge(df1, df2, on = ' ' , how = ' ' )

결합방법 : how에 넣어준다. 

1. inner : 

2. outer : 한 데이터 프레임만 있는 경우에도 다 보여줌

3. left (SQL left Outer Join 과 동일)

4. right (SQL right Outer Join 과 동일)

 

 

import pandas as pd

data1 = pd.DataFrame({
            "id" : [1, 2, 3],
   "customer_id" : [1, 2, 3],
 "customer_name" : ["Robert", "Peter", "Dave"]
}, columns = ["id", "customer_id", "customer_name"])

data2 = pd.DataFrame({
            "id" : [1, 2, 4],
      "order_id" : [100, 200, 300],
    "order_date" : ["2020-01-21", "2021-02-03", "2020-10-01"]
}, columns = ["id", "order_id", "order_date"])

print(pd.merge(data1, data2, on = 'id'))
print(pd.merge(data1, data2, on = 'id', how = 'outer'))
print(pd.merge(data1, data2, on = 'id', how = 'left'))
print(pd.merge(data1, data2, on = 'id', how = 'right'))

 

. 컬럼이 아닌 index를 기준 컬럼으로 사용하기

merge(df1, df2, left_index=True, right_index=True)

# 컬럼이 아닌 index를 기준 컬럼으로 사용하기
data1 = data1.set_index("id")
data2 = data2.set_index("id")

# index 기준으로 합치기 (inner join)
data = pd.merge(data1, data2, left_index=True, right_index=True)
print(data)

# index 기준으로 합치기 (Outer join)
data = pd.merge(data1, data2, how = 'outer', left_index=True, right_index=True)
print(data)

 

'Python' 카테고리의 다른 글

pandas 잊기 쉬운 기능 모음  (0) 2021.01.26
점프 투 파이썬 연습문제 풀기 CH2, 3  (0) 2020.12.30
그래프 그리기 Plotly  (0) 2020.09.13
Pandas  (0) 2020.09.08
Jupyter 노트북 단축키 + 기본 설명  (0) 2020.08.31