[데분스] Day+10(3). Python - Series & DataFrame, Visualization, Deleting

용솝·2024년 3월 6일
1

Python

목록 보기
3/3
post-thumbnail

파이썬 데이터 핸들링 기본(3)

1. Series & DataFrame

DataFrame은 2차원 배열 형태, Series는 하나의 컬럼 형태와 비슷

# pd.DataFrame({"컬럼":['값1','값2','값3']}) - 값이 한.개.일때에도 [대괄호] 필수!!!
df = pd.DataFrame({"name": ['Bulbasaur', 'Charmander','Squirtle','Caterpie'],
                   "evolution": ['Ivysaur','Charmeleon','Wartortle','Metapod'],
                   "type": ['grass', 'fire', 'water', 'bug'],
                   "hp": [45, 39, 44, 45],
                   "pokedex": ['yes', 'no','yes','no']})

# copy() - 데이터를 새로운 객체에 복사(깊은복사)
# df2 = df - 참조주소를 할당하기 때문에 수정에 서로 영향(얕은복사)
df2 = df.copy()

# to_csv('이름.csv') - csv로 저장()
df2.to_csv('sample.csv')

# reset_index(drop=True) - 인덱스 버리고 재설정
pd.concat([df, new_df], axis=0).reset_index(drop=True)

# np.nan - Null값을 넣어줄 때
import numpy as np
Ans.loc[[0,2],'place'] = np.nan

2. Visualization

# 시각화 세팅
# visualization libraries
import matplotlib.pyplot as plt
import seaborn as sns
# print the graphs in the notebook
%matplotlib inline
# set seaborn style to white
sns.set_style("white")

# sns.histplot(컬럼) - 히스토그램
sns.histplot(df.total_bill);

# sns.joinplot(x="컬럼1", y="컬럼2", data=데이터) - 산점도+히스토그램
sns.jointplot(x ="total_bill", y ="tip", data = df);

# sns.pairplot(데이터) - 모든 '연속형' 변수에 대한 그래프
sns.pairplot(df);

# sns.stripplot(x = "컬럼1", y = "컬럼2", hue = "컬럼3", data = 데이터) - 컬럼3 데이터 범주에 따른 색상 표현
sns.stripplot(x = "day", y = "total_bill", hue = "sex", data = df);

# sns.FacetGrid(데이터, col="컬럼1") - 패싯 그리드로 컬럼1 변수에 따른 여러 서브플롯 제작
# map(플롯, "컬럼2") - 컬럼2에 대한 플롯 그려줌
g = sns.FacetGrid(df, col = "time") # 틀
g.map(plt.hist, "tip"); # 내용

# add_legend() - 범례 표시
g.add_legend();

# sns.lmplot - 회귀선까지 기본으로 그려주는 산점도
sns.lmplot(x = 'Age', y = 'Fare', data = df, hue = 'Sex', fit_reg=False)

# np.arange(n,m,k) - n부터 m-k까지 k간격으로 array 생성
# plt.hist(데이터, bins=막대간격) 
# create bins interval using numpy
binsVal = np.arange(0,600,10)
plt.hist(df2, bins = binsVal)

3. Deleting

# del - 컬럼 삭제
del df['class']
# del 은 복구 안되니, 재할당 추천
# df = df[['sepal_length',	'sepal_width',	'petal_length',	'petal_width']]

# dropna(how='any') - 하나라도 NaN있는 행 삭제
df.dropna(how='any')

profile
🖐

0개의 댓글