
pd.DataFrame(data [, index=None, colmns=None])
# 학생들의 시험 점수를 담은 DataFrame을 만들어보자
import pandas as pd
# pandas의 alias(별칭)은 관례적으로 pd 사용
g = {
"number":["student-"+str(i) for i in range(1, 11)],
"국어":[100, 83, 92, 75, 80, 93, 87, 67, 71, 59],
"수학":[78, 67, 92, 100, 95, 67, 82, 98, 75, 100]
}
grade = pd.DataFrame(g)
DataFrame 객체.to_csv(파일경로, sep=[구분자], index=[True/Flase], header=[True/Flase]) # 양수 index name, colum name 저장 안 함
grade.to_csv("save_data/grade.csv",
index=False, header=False)
# 양수 index name, colum name 저장함, 미입력 시 기본값 True
grade.to_csv("save_data/grade.csv",
index=True, header=True)
# 양수 index name, colum name 저장함, 구분자 "\t", 미입력 시 기본값 ","
grade.to_csv("save_data/grade.csv", sep="\t")
엑셀로 저장
DataFrame 객체.to_csv(파일경로, index=[True/Flase], header=[True/Flase])
Database Table에 저장
DataFrame 객체.to_csv(파일경로, index=[True/Flase], header=[True/Flase])
import pandas as pd
from sqlalchemy import create_engine # 모듈 필요
user = "[sql user 이름]"
password = "[sql pw]"
host = "localhost"
port = 3306
database = "[값을 추가할 database명]"
conn_str = f"mysql+pymysql://{user}:{password}@{host}:{port}/{database}"
# DB 연결
engine = create_engine(conn_str)
# 데이터 insert (append 모드)
grade.to_sql(
name="grade", # 값을 넣을 Table명
con=engine, # connection
if_exists="append", # 테이블 존재 시 데이터 추가,
"replace": 테이블 삭제후 다시 생성
"fail": 테이블이 있으면 에러
index=False # index는 저장하지 않음
)
grade.to_pickle("saved_data/grade.pickle")grade.to_html("saved_data/grade.html")grade.to_json("saved_data/grade.json")가능함파일경로: 읽어올 파일의 경로sep: 구분자, 기본값 commaheader: 컬럼명으로 사용할 행 지정, 기본값 첫 번째 행, None으로 지정할 경우 파일의 첫 번째 행부터 값으로 사용하고 컬럼명은 0부터 자동증가하는 값 입력index_col: index명으로 사용할 열 이름이나 순번 지정, 생략 시 0부터 자동증가하는 양수 index 입력na_values: 결측치로 처리할 문자열 지정 a = pd.read_csv(
"data/abc1.csv",
sep=",",
header=0)
a
DataFrame객체.set_index(컬럼 이름, inplace= )
inplace : 원본 변경 여부, True/False로 입력DataFrame객체.reset_index(drop=False, inplace= )
조회
DataFrame객체.columsDataFrame객체.index변경 DataFrame객체.colums = ['새 이름', '새 이름', ..., '새이름]
method 이용
DataFrame객체.rename(index={"기존 이름":"변경할 이름"},
colunms={"기존 이름":"변경할 이름"}, inplace= )
inplace : 원본 변경 여부, True/False로 입력삭제
DataFrame객체.drop(colums= , index= , inplace= )
columns : 삭제할 열 이름 또는 열 이름 리스트 (여러 개일 경우)index: 삭제할 index명 또는 index 리스트inplace : 원본 변경 여부, True/False로 입력DataFrame객체.drop_duplicates()
subset='컬럼명', subset=['c1', 'c2', ...] Parameter를 활용해 중복 기준 컬럼 지정 가능 import pandas as pd
# DataFrame 생성
col = ['col1', 'col2', 'col3']
values = [
['A', 'a', '1'],
['B', 'b', '1'],
['A', 'b', '2'],
['B', 'b', '1'],
['A', 'a', '2'],
['A', 'b', '2'],
]
a = pd.DataFrame(data=values, columns=col)
a
# 출력 결과
col1 col2 col3
0 A a 1
1 B b 1
2 A b 2
3 B b 1
4 A a 2
5 A b 2
subset 미지정 # 중복행 제거
a.drop_duplicates()
# 출력 결과
col1 col2 col3
0 A a 1
1 B b 1
2 A b 2
4 A a 2
subset 지정 # 중복행 제거
a.drop_duplicates(subset = "col3")
# 출력 결과
col1 col2 col3
0 A a 1
2 A b 2
컬럼 추가
DataFrame객체['추가할 컬럼명'] = [컬럼에 넣을 값 (list로)]
열 삽입
DataFrame객체.insert(삽입할 위치의 index, '삽입할 컬럼명', 값)
파생변수 생성
`DataFrame객체['추가할 컬럼명'] = 연산
# DataFrame 생성
col = ['수학1', '수학2', '미적분']
values = [
[95, 94, 88],
[88, 92, 85],
[95, 90, 92],
]
a = pd.DataFrame(data=values, columns=col)
a
# 출력 결과
수학1 수학2 미적분
0 95 94 88
1 88 92 85
2 95 90 92
# 파생변수 생성
a['수학 과목 평균'] = (a['수학1'] + a['수학2'] + a['미적분'])//3
a
# 출력 결과
수학1 수학2 미적분 수학 과목 평균
0 95 94 88 92
1 88 92 85 88
2 95 90 92 92
행 조회
행 이름으로 조회
DataFrame객체.loc[index 이름]DataFrame객체.loc[index 이름 리스트]DataFrame객체.loc[start index 이름 : end index 이름 : step(간격)]DataFrame객체.loc[index 이름, 컬럼 이름]행 순번으로 조회
DataFrame객체.iloc[행번호]DataFrame객체.iloc[ 행번호 리스트 ]DataFrame객체.iloc[start 행번호: stop 행번호: step]DataFrame객체.iloc[행번호 , 열번호]컬럼 조회
DataFrame객체['컬럼명'] 컬럼명 아래의 값들을 조회DataFrame객체.컬럼명 컬럼명이 Python 식별자 규칙에 맞는 경우 .표기법 사용 가능DataFrame객체[조건], DataFrame객체.loc[조건]
&(and), |(or), ~(not) 사용 가능, 단 사용 시 연산자들을 ()로 묶어줘야 함