반응형

여러 데이터 비교를 위한 결과 HTML 수정

Jupyter Notebook을 이용하여 두 데이터를 비교해서 확인 하고 싶은 경우가 있다.

물론 두 데이터를 print() 함수와 display() 함수를 이용하여 수직적으로 확인할 수 있겠지만

데이터의 양이 많을 경우 수직적으로 나타내는 데이터는 확인이 어렵다.

아래 작업을 통해 HTML을 수정함으로써 데이터의 양이 많더라도 수평적으로 쉽게 데이터를 비교할 수 있다.


 Source Code

from IPython.display import display_html
def display_side_by_side(*args):
    html_str=''
    for df in args:
        html_str += df.to_html()
    display_html(html_str.replace('table','table style="display:inline"'), raw=True)

 예시) 여러 데이터프레임 결과 비교

반응형
반응형

 두 데이터프레임의 결과를 비교하기 위한 준비

display_side_by_side 함수는 여러데이터를 비교하기 위해 생성한 함수이다.

(아래 링크에서 자세한 내용 확인)

 

[Python] 여러 데이터 비교를 위한 결과 HTMl 수정

여러 데이터 비교를 위한 결과 HTMl 수정 Jupyter Notebook을 이용하여 두 데이터를 비교해서 확인 하고 싶은 경우가 있다. 물론 두 데이터를 print() 함수와 display() 함수를 이용하여 수직적으로 확인할

hyunmin1906.tistory.com

Soruce Code

 

hyunmin94/hyunmin

Contribute to hyunmin94/hyunmin development by creating an account on GitHub.

github.com


 데이터프레임(DataFrame) 병합

※ (1~4번) 기준 두개의 DataFrame 데이터 준비

 merge 함수

두 데이터프레임을 기준열 혹은 index를 이용하여 병합할때 사용한다.


1) inner join

두 데이터프레임에서 공통적으로 존재하는 열의 데이터를 기준으로 inner 병합한다.

Default
on = "사원번호"
how = "inner"

2) outer join

  • 공통적으로 존재하는 열을 기준으로 두 데이터프레임의 전체 데이터를 병합
  • 공통적으로 존재하지 않는 열의 데이터는 NaN으로 자동처리 된다.
빨간색 : 두 데이터프레임 중 한쪽에만 존재하는 데이터

3) left join

기준열에서 공통적인 데이터와 왼쪽에 위치한 데이터프레임의 데이터를 병합

빨간색 : 공통적인 데이터를 제외하고 왼쪽 데이터프레임에 존재하는 데이터만 병합된걸 알 수 있다.

4) right join

기준열에서 공통적인 데이터와 오른쪽에 위치한 데이터프레임의 데이터를 병합

빨간색: 공통적인 데이터를 제외하고 오른쪽 데이터프레임에 존재하는 데이터만 병합된걸 알 수 있다.


※ (1~2번) 기준 두개의 DataFrame 데이터 준비

1) left_on, right_on

공통적인 열은 없지만 양쪽의 공통적인 데이터형식을 갖고 있으며, 이를 이용하여 조인하고 싶을 경우 사용 

2) left_index, right_index

데이터프레임의 index 값을 통해 join을 하기 위해 기준 데이터의 index를 join 하고자 하는 열로 지정함


■ join 함수

두 데이터프레임의 index를 기준으로 join이 이루어진다.



■ concat 함수

단순히 데이터를 연결할때 사용한다.


열로 데이터 연결(병합)

행으로 데이터 연결(병합)

반응형
반응형

※ 결과 비교를 위한 html 수정

from IPython.display import display_html
def display_side_by_side(*args):
    html_str=''
    for df in args:
        html_str += df.to_html()
    display_html(html_str.replace('table','table style="display:inline"'), raw=True)

※ 기준 DataFrame데이터 준비

import pandas as pd # 실습할 판다스 버전: 1.0.1

data = {"name": ["Atom", "John", "Park", "Kim"], 
        "weight": [50, 60, 80, 30],
        "height": [150,180,170,200]}

people_df = pd.DataFrame(data)
display(people_df)

1) 비교연산자(==) 사용

str_expr = "weight == 50"
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 몸무게가 50인 데이터")
display_side_by_side(people_df, people_df_q)


2) 비교연산자(!=) 사용

str_expr = "height != 150"
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 키가 150이 아닌 데이터")
display_side_by_side(people_df, people_df_q)


3) 비교연산자(<,<=,>,>=) 

str_expr = "weight < 60" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("※ 비교연산자(<)")
print("조건 : 몸무게가 60미만인 데이터")
display_side_by_side(people_df, people_df_q)

str_expr = "weight <= 60" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("※ 비교연산자(<=)")
print("조건 : 몸무게가 60이하인 데이터")
display_side_by_side(people_df, people_df_q)

str_expr = "weight > 60" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("※ 비교연산자(>)")
print("조건 : 몸무게가 60초과인 데이터")
display_side_by_side(people_df, people_df_q)

str_expr = "weight >= 60" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("※ 비교연산자(>=)")
print("조건 : 몸무게가 60이상인 데이터")
display_side_by_side(people_df, people_df_q)


4) in 연산자( in, ==)

  • in 과 == 의 결과는 같다 
  • 다수의 조건데이터는 리스트[] 또는 튜플() 형태로 사용가능
str_expr = "weight in [60,30]" # 같은 결과 "weight == [60,30]" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 몸무게가 30 이거나 60인 데이터")
display_side_by_side(people_df, people_df_q)


5) not in 연산자( not in, !=)

  • not in 과 != 의 결과는 같다 
  • 다수의 조건데이터는 리스트[] 또는 튜플() 형태로 사용가능
str_expr = "weight != 30" # 같은 결과 "weight not in 30" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 몸무게가 30이 아닌 데이터")
display_side_by_side(people_df, people_df_q)


6) 논리 연산자(and, or, not)

  • and : 전체 조건이 참일경우 참 
  • or : 전체 조건 중 하나라도 참일경우 참 
  • not : 뒤에 오는 조건의 반대(참일경우 거짓, 거짓일경우 참)
str_expr = "(weight > 50) and (weight <80)"
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("※ and 연산자")
print("조건 : 몸무게가 50보다 크고 80보다 작은 데이터")
display_side_by_side(people_df, people_df_q)

str_expr = "(weight == 50) or (weight > 60)"
print("※ or 연산자")
print("조건 : 몸무게가 50이거나 60보다 큰 데이터")
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
display_side_by_side(people_df, people_df_q)

str_expr = "not (weight == 50)"
print("※ not 연산자")
print("조건 : 몸무게가 50이 아닌 데이터")
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
display_side_by_side(people_df, people_df_q)


7) 외부 변수 참조 연산

num_weight = 70
num_height = 200
str_expr = "(weight > @num_weight) and (height <= @num_height)"
print("조건 : 몸무게가 70보다 크고 키가 200보다 작은 데이터")
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
display_side_by_side(people_df, people_df_q)


8) f-String을 이용한 외부 변수(또는 함수) 참조 연산

num_weight = 70
num_height = 200
str_expr = f"(weight > {num_weight}) and (height <= {num_height})"
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 몸무게가 70보다 크고 키가 200보다 작은 데이터")
display_side_by_side(people_df, people_df_q)


9) 함수를 이용한 참조 연산

def weight_min(data):
    return min(data)

num_weight = 70
str_expr = "weight > @weight_min([70,90,30,50])" # 몸무게가 30보다 큰 데이터
print("조건 : 몸무게가 리스트데이터([70,90,30,50]) 중 최저값보다 큰 데이터")
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
display_side_by_side(people_df, people_df_q)


10) 인덱스 검색 

  • 인덱스이름이 있다면 index대신 이름(DataFrameObj.index.name)을 기입합니다. 
str_expr = "index > 1" 
people_df_q = people_df.query(str_expr) # 조건 부합 데이터 추출
print("조건 : 인덱스(index)가 1보다 큰 데이터")
display_side_by_side(people_df, people_df_q)


11) (비교문자열)컬럼명.str.contains

▶ query 함수 옵션

  • engine : python

▶ contains 함수 옵션

  • case : True (대소문자 구별, 디폴트), False(대소문자 구별 안함) 
str_expr = 'name.str.contains("a")' 
people_df_q = people_df.query(str_expr, engine="python") # 조건 부합 데이터 추출
print("※ 대소문자 구별")
print("조건 : 이름에 'a'가 들어가 있는 데이터")
display_side_by_side(people_df, people_df_q)

str_expr = 'name.str.contains("a",case=False)' 
people_df_q = people_df.query(str_expr, engine="python") # 조건 부합 데이터 추출
print("※ 대소문자 구별 안함")
print("조건 : 이름에 'a'가 들어가 있는 데이터")
display_side_by_side(people_df, people_df_q)


12) (비교문자열)컬럼명.str.startswith

str_expr = 'name.str.startswith("P")' 
people_df_q = people_df.query(str_expr, engine="python") # 조건 부합 데이터 추출
print("조건 : 이름이 'P' 로 시작하는 데이터")
display_side_by_side(people_df, people_df_q)


13) (비교문자열)컬럼명.str.endswith

str_expr = 'name.str.endswith("m")' 
people_df_q = people_df.query(str_expr, engine="python") # 조건 부합 데이터 추출
print("조건 : 이름이 'm' 로 끝나는 데이터")
display_side_by_side(people_df, people_df_q)


SOURCE CODE

 

hyunmin94/hyunmin

Contribute to hyunmin94/hyunmin development by creating an account on GitHub.

github.com

반응형
반응형

■ CSV 파일 쓰기(저장)

  • {파일이름} : 파일의 경로와 이름을 지정
  • {데이터} : 배열,리스트, 데이터프레임 등 여러데이터 형식의 데이터 입력 가능
  • {데이터 형식} : 정규 표현식으로 데이터의 형식을 지정한다
  • {데이터간 구분자} : 파일에 입력하고자 하는 데이터간의 구분자를 지정
numpy.savetxt({파일이름}, {데이터}, fmt={데이터 형식}, delimiter={데이터간 구분자})

 

▶ 설치 경로에 파일 확인

▶ 파일 데이터 확인

정수타입의 데이터 이며, 반점(,)을 구분자로 작성된 데이터를 확인가능

 


■ CSV 파일 읽기(불러오기)

▶ 파일 데이터 확인

▶ CSV파일 읽기

  • {파일 이름} : 읽고자하는 파일의 경로와 이름을 지정
  • {구분자} : 읽고자하는 파일의 구분자와 동일하게 지정한다
  • {데이터 형식} : 읽고자하는 데이터의 형식을 지정 예) 정수 : np.int 혹은 'i'
numpy.loadtxt({파일 이름}, delimiter={구분자}, dtype={데이터 형식})

 


■ Numpy 객체형태(npy)로 파일 쓰기(저장)

  • {파일 이름} : Numpy 객체 형태이며, 확장자는 '.npy' 이고, Binary 파일 형태로 저장됩니다
  • {배열} : array 형식의 배열
np.save({파일 이름}, arr={배열})

 

▶ 설치 경로에 파일 확인

▶ (생략) 파일 데이터 확인

파일이 Binary 형태이므로 메모장이나, 노트패드로 열면 깨짐현상 때문에 확인이 어려움 

■ Numpy 객체형태(npy)로 파일 읽기(불러오기)

▶ (생략) 파일 데이터 확인

파일이 Binary 형태이므로 메모장이나, 노트패드로 열면 깨짐현상 때문에 확인이 어려움

▶ Numpy 객체형태(npy)로 파일 읽기

배열변수 = np.load(file={파일 이름})

 

반응형
반응형

리스트 슬라이싱

[리스트] 데이터 확인

[리스트] 슬라이싱

1) listObj[:끝 인덱스]

예시) index 가 0 이상 3미만의 데이터 추출

2) listObj[시작 인덱스:]

예시) index 가 2 이상부터 마지막인덱스까지의 데이터 추출

 

3) listObj[시작 인덱스 : 끝인덱스]

예시) index 가 1 이상부터 마지막 인덱스 전까지의 데이터 추출

 


배열 슬라이싱

[배열] 데이터 확인

[배열] 슬라이싱

1) arrObj[시작인덱스: 끝인덱스]

예시) index가 0 이상 2 미만의 데이터 추출

도움말

  • arr[0] = [1,2,3]
  • arr[1] = [4,5,6]
  • arr[2] = [7,8,9]

2) arrObj[행 시작index: 행 끝index, 열 시작index: 열 끝index]

예시) 행 index 0 이상 2 미만, 열 index 1 이상 3 미만의 데이터 추출

※ 도움말

  • arr[0:2, 1] = [2,5]
  • arr[0:2, 2] = [3,6]

3) arrObj[행 시작index: 행 끝index][행 시작index: 행 끝index]

예시) 행 index 1 이상 3 미만 데이터를 기준으로 다시 행 index 1 이상 2 미만 데이터 추출

※ 도움말

  • arr[1:3][0] = [4, 5, 6]
  • arr[1:3][1] = [7, 8, 9]


 데이터프레임 슬라이싱

[데이터프레임] 데이터 확인

[데이터프레임] 슬라이싱

1) DataFrameObj[행 시작index: 행 끝index]

예시) 행 index가 1 이상 3 미만의 데이터 추출

 

2) DataFrameObj[행 시작이름: 행 끝이름]

예시) 행 이름이 'b' 부터 'c' 까지의 데이터 추출

 

3) DataFrameObj[행 시작index : 행 끝index][행 시작index : 행 끝index]

예시) 행 index가 1 이상 3미만의 데이터를 기준으로 다시 행 index 1 이상 2 미만 데이터 추출

※ 도움말

  • '1) DataFrameObj[행 시작index: 행 끝index]' 의 예시 참고

4) DataFrameObj.loc[행 시작이름:행 끝이름, 열 시작이름: 열 끝이름]

 

! 주의 index로 슬라이싱 불가

예시) 행 이름이 'b' 이상 'c'이하이고, 열 이름이 'B' 이상 'C' 이하의 데이터 추출

 

5) DataFrameObj.loc[행 시작이름:행 끝이름][행 시작이름:행 끝이름]

예시) 행 이름이 'a' 이상 'c'이하인 데이터를 기준으로 행 이름이 'b' 이상 'c'이하의 데이터 추출

 

6) DataFrameObj.iloc[행 시작index:행 끝index, 열 시작index: 열 끝index]

 

! 주의 행과열의 이름으로 슬라이싱 불가 ( loc 인덱서와 반대 )

예시) 행 index가 0 이상 2 미만 이고, 열 index가 1 이상 3 미만의 데이터 추출

 

7) DataFrameObj.iloc[행 시작index:행 끝index][행 시작index:행 끝index]

예시) 행 index가 0 이상 3미만 인 데이터를 기준으로 행 index가 1 이상 3 미만의 데이터 추출

 

반응형
반응형

리스트 데이터 인덱싱

[리스트] 데이터 확인

[리스트] 인덱싱

예시) 6 추출
  • list[1] = [4, 5, 6]
  • list[1][0] = 4
  • list[1][1] = 5
  • list[1][2] = 6


 배열 데이터 인덱싱

[배열] 데이터 확인

[배열] 인덱싱

예시) 6 추출

 

 

1) arrObj[행 인덱스][열 인덱스]

 

2) arrObj[행 인덱스, 열 인덱스]

 

3) arrObj[[행 인덱스, 열 인덱스]]

예시) 배열형식으로 6 추출

 


 데이터프레임 데이터 인덱싱

[데이터프레임] 데이터 확인

[데이터프레임] 인덱싱

예시) 6 추출

 

 

1) DataFrameObj[열 이름][행 이름]

 

2) DataFrameObj.loc[행 이름][열 이름]

 

3) DataFrameObj.loc[행 이름, 열 이름]

 

4) DataFrameObj.iloc[행 인덱스][열 인덱스]

 

5) DataFrameObj.iloc[행 인덱스, 열 인덱스]

 

6) DataFrameObj.loc[[행 이름], [열 이름]]

예시) DataFrame형식으로 6 추출

 

 

7) DataFrameObj.iloc[[행 인덱스], [열 인덱스]]

반응형

+ Recent posts