[Pandas] 데이터 불러오기, 저장하기 / Serise와 DataFrame
[Pandas] 데이터 불러오기, 저장하기 / Serise와 DataFrame
01. [Pandas] 데이터 불러오기 & 저장하기
데이터 불러오기 & 저장하기
csv 불러오기
- Comma Seperated Values
csv 파일 불러오기
1
2
3
4
5
import pandas as pd
csv_file_path = "./data/titanic_train.csv"
df_csv = pd.read_csv(csv_file_path)
df_csv
1
2
# index_col을 사용해서 인덱스 지정하기
df_csv = pd.read_csv("./data/titanic_train.csv", index_col = "PassengerId")
데이터프레임 정보 확인
1
df_csv.info()
데이터의 일부 정보만 확인
1
2
df_csv.head() # 상위 5개의 정보 확인
df_csv.tail(10) # 하위 10개의 정보 확인
웹 html 파일 불러오기
- 웹 페이지의 table태그(표)를 데이터 프레임으로 받아 올 수 있다.
1
!pip install lxml html5lib
1
2
3
4
5
6
html_path = "https://finance.naver.com/sise/sise_quant.naver"
# utf-8이 기본! 안되면 euc-kr, 이것도 안되면 cp949, 이것도 안되면 엑셀로
html_data_list = pd.read_html(html_path, encoding ='euc-kr')
html_data_list
- html은 csv와 excel과 다르게 list형식으로 불러와지는 듯한
1 2 3
df_kospi = html_data_list[1] df_kospi.head() # NaN : 값이 없다는 뜻
1 2 3
# 모든 값이 NaN이라면 해당 행을 삭제한 후, index를 다시 매긴다. (삭제된 index는 dataframe에 남기지 않고 drop한다.) df_processed = df_kospi.dropna(how="all").reset_index(drop=True) df_processed
파일 저장하기
1
2
# dataframe을 csv로 저장하는 명령어, 저장할 파일의 경로와 이름도 지정
df_processed.to_csv("./data/kospi_processed_20250113.csv", encoding="utf-8")
02. [Pandas] Serise와 DataFrame
설명
- Series : 한 항목의 Data들 모아둔 것
- DataFrame : 이러한 Series들을 모아둔 것 (2차원 배열, matrix 느낌)
- Pandas는 이 것들을 도와주는 하나의 도구
- 열 index는 다른 말로 column , column index
사전준비
1
import pandas as pd
Series 생성하기
dict를 이용해 Series 만들기
1
2
3
sample_dict = {"a" : 1, "b" : 2, "c" : 3}
dict_serise = pd.Series(sample_dict)
dict_series
list를 이용해 series 만들기
1
2
3
4
# 인덱스를 따로 지정해주지 않으면 자동으로 range index 생성됨.(마치 offset index 같은 것)
lst = [1,2,3]
list_series = pd.Series(lst, index = ["a", "b", "c"])
list_series
Series에 이름 넣기
1
2
list_series3 = pd.Series(lst, name = "컬럼 이름!")
list_series3
DataFrame
- 시리즈를 모아놓은 것
dict로 DataFrame 생성
1
2
3
4
5
6
# Values에 데이터 개수가 같아야 DataFrame 생성
sample_dict = {
"Name" : ["A", "B", "C"],
"height" : [169.3, 180.2, 177.8]
}
df = pd.DataFrame(sample_dict)
list로 DataFrame 생성
- 리스트로 데이터프레임을 만들 땐, 당연히 2차원 배열이어야 함.
1
2
3
4
5
lst = [["A", 169.3],
["B", 180.2],
['c', 177.8]]
df = pd.DataFrame(lst, columns = ["Name", "Height"])
df
series를 합쳐서 DataFrame 생성
1
2
3
4
5
6
name_series = pd.Series(['A', "B",'C'])
height_series = pd.Series([169.3, 180.2, 177.8])
# 시리즈를 컬럼 이름과 함께 dict형태로 만들어 넣는다.
df = pd.DataFrame({"name": name_series, "height": height_series})
df
JsonArray 형식으로 된 데이터를 DataFrame으로 만들기.
- 진짜 많이 사용
1
2
3
4
5
6
json_sample_array = [
{"name" : "A", "height": 180.3},
{"name" : "B", "height": 178.6}
]
df = pd.DataFrame(json_sample_array)
df
This post is licensed under CC BY 4.0 by the author.