Mar 7, 2023

[Python] pandas.DataFrame 활용 (Usage pandas.DataFrame)


# reference: https://pandas.pydata.org/docs/user_guide/10min.html

import pandas as pd

# Loading data
df_LH_apt = pd.read_csv("C:\\Users\\user\\Desktop\\sw_data\\LH_apt_20220722.csv", encoding='CP949') # ./: current working directory
df_LH_apt
Output

# Viewing data from 0 row to 5 row
df_LH_apt.head()
Output

# Viewing data from n-4 to n row, n: last index
df_LH_apt.tail()
Output

# Total index
df_LH_apt.index

# Total columns
df_LH_apt.columns


# Total data types
df_LH_apt.dtypes
Output

# Choosing number style column
df_LH_apt.select_dtypes(include = "number")
Output

# Choosing object style column
df_LH_apt.select_dtypes(include = "object")

# Select "세대수" column
df_LH_apt["세대수"] # or df_LH_apt.세대수
df_LH_apt[["세대수", "동수", "주소"]] # multi-column

df_LH_apt_piece = df_LH_apt.copy()[10:18]
df_LH_apt_piece
Output


# DataFrame에 할당된 index 기준
df_LH_apt_piece.loc[10, :]
Output

# DataFrame에 있는 순서 기준, 내부 index는 slicing 문법 적용
df_LH_apt_piece.iloc[0, :]
Output

# 데이터 접근, row에 slicing, column에 특정 변수
df_LH_apt.loc[4:8, ["세대수", "준공일"]] # or df_LH_apt[4:8][["세대수", "준공일"]]
# 데이터 접근, row과 column에 slicing
df_LH_apt.loc[4:8, '세대수' : '준공일']
# 데이터 접근, 모든 row
df_LH_apt.loc[:, '세대수' : '준공일']
# 데이터 접근, row에 slicing, 모든 column
df_LH_apt.loc[4:8, :]

# '단지'로 시작하는 columnes
df_LH_apt.filter(regex='^단지')
Output

# 내부 조건에 해당하는 데이터 선택
df_LH_apt[df_LH_apt["세대수"] > 1500]

# 여러개의 내부 조건이 있는 경우, 즉, & or | 조건에 해당하는 데이터 선택
df_LH_apt[(df_LH_apt["세대수"] > 1500) & (df_LH_apt["동수"] < 30)]
df_LH_apt[(df_LH_apt["세대수"] > 1500) | (df_LH_apt["동수"] < 30)]

# 해당 column에 있는 값 유형 확인
df_LH_apt["주택유형"].unique()
Output

# 해당 column에 특정 값 유형 있는 데이터를 산출
df_LH_apt[df_LH_apt["주택유형"].isin(["공공임대(10년)", "임대상가"])]

# 해당 column 기준 가장 큰 값 5개, 같은 값을 때 모두 포함해서 표시
df_LH_apt.nlargest(5, "동수", keep= "all")

# 해당 column 기준 가장 작은 값 5개, 같은 값을 때 모두 포함해서 표시
df_LH_apt.nsmallest(5, "동수", keep= "all")

# 해당 column값에 따른 오름차순 정렬, default가 오름차순
df_LH_apt.sort_values("세대수") # or df_LH_apt.sort_values("세대수", ascending = True)
# 해당 column값에 따른 내림차순 정렬
df_LH_apt.sort_values("세대수", ascending = False)
# 여러 column을 기준으로도 정렬 가능
df_LH_apt.sort_values(["세대수", "동수"], ascending = [False, False])

# index 기준 재정렬
df_LH_apt.sort_index()

No comments:

Post a Comment