스터디노트 5월 21일

Jenny·2024년 5월 22일

05 Time Series

# datetime64 타입
df.Yr-Mo-Dy = pd.to_datetime (df.Yr-Mo-Dy)

# datetime.date
fix_century = pd.to_datetime(datetime.date (year, month, day)

# dt.to_period('M')
df.groupby(df.Yr-Mo-Dy.dt.to_period('M')).mean(numeric_only=True)

dt.year
df.Yr-Mo-Dy.dt.year.unique()

dt.month
dt.hour
dt.weekday	# Mon:0, Sun:6
dt.day_name()	# Mon: Monday, Sun: Sunday
df [ 'dayname' ] = 'df['Y-M-D'].dt.day_name()

# timedelta
pd.to_datetime ('2024-05-21 00:00:00')
+ daytime.timedelta (days=1)

# 시간을 차분한 경우, 첫 값은 Nan, 이후 모든 값이 동일하면 연속이라 판단한다.
len (df ['Y-M-D'].diff().unique())
=> 2

# moving average
df [[ col1, col2 ]].rolling(7).mean()

df.set_index ('Y-M-D', inplace=True)

06 Pivot

df.drop ['col', axis=1, inplace=True]

data.pivot (index = 'Location', columns = 'Period', values = 'First')
df.pivot_table (index = 'Dim1', columns='Period', values = 'First', aggfunc='mean')
df.pivot_table (index = 'year', columns = 'medal', aggfunc = 'size').fillna(0)
  • pivot과 pivot_table 차이가 뭘까?

07 Merge, Concat

pd.concat ( [df1, df2], axis=0)	# 행으로 붙이기
pd.concat ( [df3, df4], join='inner')
pd.concat ( [df3, df4], join='outer').fillna(0)

pd.merge (df5, df6, on='Al', how='inner')
pd.merge (df5, df6, on='Al', how='outer').fillna(0)

08 Stats

del df [ 'colName' ]

df.head()
df [ 'colName' ].value_counts()
df.sort_values (by=['col1'], ascending=0)

df [ 'colName' ].nunique()
df.col.min()
df.col.max()
df.col.median()
df.col.std()
df.describe()

09 Series & DataFrame

df = pd.DataFrame ({ 'name' : [ 'name1', 'name2', 'name3' ],
'type' : [ 'type1', 'type2', 'type3' ],
'hp' : [ 45, 35, 55 ]})

df.index = ['one', 'two', 'three']
df.set_index ('name', inplace=True)

import os
os.getcwd ()
os.chdir ('path')
df.to_csv ('fileName.csv')

import numpy as np
df.loc [ [0,2], 'place' ] = np.nan

10 Visualization

import matplotlib.pyplot as plt
import seaborn as sns
%matplotlib inline

ttbill = sns.histplot (df.col)
ttbill.set (xlabel = 'val', ylabel = 'freq', title = 'total')

sns.jointplot (x='total', y='tip', data=df)
sns.pairplot (df)

sns.stripplot (x='col1', y='col2', data=df)
sns.stripplot (x='col1', y='col2', hue='col3', data=df)

sns.boxplot (x='col1', y='col2', hue='col3', data=df)

## two histograms
sns.set (style='ticks')
g = sns.FacetGrid (df, col='col2')
g.map (plt.hist, 'col1')

## two scatter plots
g = sns.FacetGrid (df, col='gender', hue='smoker')
g.map (plt.scatter, 'total', 'tip', alpha=.7)
g.add_legend()

## pie chart
plt.pie (proportions, labels=['col1', 'col2'], shadow=False, colors=['blue', 'red'], explode=(0.15, 0), startangle=90, autopct='%1.1f%%')
plt.axit ('equal')
plt.title ('Proportion')
plt.tight_layout ()
plt.show ()

## 산점도
lm = sns.lmplot (x='col1', y='col2', data=df, hue='col3', fit_reg=False)	#fit_reg=True : regression line
lm.set (title='Graph Title')
axes = lm.axes
axes [0,0].setylim (-5,)
axes [0,0].setxlim (-5, 85)

## Histogram with bins
import numpy as np
binsVal = np.arrange (0, 600, 10)
plt.hist (df, bins=binsVal)
plt.xlabel ('X')
plt.ylabel ('Y')
plt.title ('Graph Title')
plt.show ()

11 Deleting

df.iloc [9:29, 2] = np.nan
df.dropna (how='any')
  • 눈으로 주로 보다가 손으로 타이핑 하기 시작하니 '읽기'에서 '쓰기'로 넘어가는 단계를 실감하고 있는 것 같다. 손에 익을 때까지는 자동 완성 보다 직접 쓰는 습관을 먼저 가져보아야겠다.

이 글은 제로베이스 데이터 분석 취업 스쿨의 강의자료 일부를 발췌하여 작성되었습니다.

profile
I like to movie movie

0개의 댓글