[SSUDA] 빅데이터 분석 과목 코드 정리
from google.colab import drive
drive.mount('/content/drive')
path = '/content/drive/MyDrive/bigdatas/'
import numpy as np
ar1= np.arange(15).reshape(3,5) # arange, reshape
ar1
A = np.array([[1,2], [3,4]])
B = np.array([[2,3], [4,5]])
A@B # 넘파이 내적연산
np.random.randn(3,2)
np.random.randint(1, 100, size=6).reshape(3,2)
B = np.arange(12).reshape (3,4)
B
B.sum(axis=0) # 열 기준 연산
B.mean(axis=1) # 행 기준 연산
x = np.arange(30).reshape((5,6))[:,::2] # 열 기준 0,2,4 컬럼 뽑기
x
import pandas as pd
# 데이터프레임 딕셔너리로 만들기
dic= { 'gender' : [ 1, 2, 1,2], 'bloodtype': ["A", "B", "O", "AB"]}
df1= pd.DataFrame(dic)
df1
dates = pd.date_range("20210309", periods=6)
# 데이터프레임 넘파이로 만들기
df = pd.DataFrame(np.random.randn(6, 4), index= dates, columns=list("ABCD"))
df
df.tail() # 밑에서부터 5개 출력
df.describe()
df.sort_values(by="B") # B 기준으로 정렬
df=pd.read_csv(path + "studentlist.csv", encoding="cp949")
df
df[0:3]
df[["age", "grade"]]
df.iloc[1:5, 0:3] # 행, 열
df.loc[df["bloodtype"].isin( ["B", "A"] ), ["name", "age"]]
df2 = df[1:3] # 2개 row
df3 = df[5:8]
df4 = pd.concat([df2, df3], axis=0) # 행 기준으로 합체
df4
dff= pd.read_csv(path+"footsize.csv", encoding="cp949")
df3= pd.merge(df, dff, left_on='name', right_on='realname')
df3
df.groupby(["sex","bloodtype"]).mean()
import matplotlib.pyplot as plt
plt.plot( df[["height", "weight"]] )
plt.plot( df["height"], df["weight"] , 'gs') # 색깔/기호(o, ^, s, -, --)
names = ['group_a', 'group_b', 'group_c'] # X
values = [1, 10, 100] # Y
plt.figure(figsize=(7, 3)) #전체 가로세로 크기
plt.subplot(231) # 2 x 3 구성의 1번
plt.bar(names, values)
plt.subplot(232)
plt.scatter(names, values)
plt.subplot(236)
plt.plot(names, values)
plt.suptitle('Categorical Plotting')
plt.scatter ( "height", "weight", c="grade" ,data=df) # c : 유형별 컬러 다르게
import seaborn as sns
import pandas as pd
titanic= sns.load_dataset("titanic")
# 클래스 별로 점 색깔 다르게 하기.
sns.scatterplot(x = 'fare', y = 'age', data = titanic, hue='class')
titanic.to_csv("titanic.csv", index=False)
titanic.info()
print(titanic.dtypes)
print()
titanic.dtypes [ titanic.dtypes==np.int64 ]
titanic['survived'].astype(float)
titanic.sex.value_counts(normalize=True)
titanic.survived.value_counts().plot(kind='pie') # 'bar'
sns.countplot(x='survived', data=titanic)
print(titanic['fare'].quantile(0.5), titanic['fare'].quantile(0.75))
plt.boxplot(titanic.fare, vert=False)
numeric_columns = ['age', 'fare']
for i in range(1,3):
c = numeric_columns[i-1]
plt.subplot(2,1,i)
plt.title(c)
plt.boxplot(titanic[c].dropna(), vert=False) # vert : 세로로 하기
plt.show()
sns.histplot(x='fare', data=titanic, bins=[0,100,200,300,400,500,600]) # 또는 bins= 갯수
titanic.dropna(subset=['age'])
titanic.age.fillna( titanic.age.median()) # 중앙값 대체
pd.Categorical( titanic.who, categories=["man", "woman"])
import scipy.stats as st
import numpy as np
sample1=titanic.sample (n=30)
sample2=titanic.sample (frac=0.2)
# 소규모 t검정 자유도 n-1
print ("sample1:", np.mean(sample1.fare), st.t.interval(alpha=0.95, df=len(sample1)-1, loc=np.mean(sample1.fare), scale=st.sem(sample1.fare)))
# 대규모 정규분포 검정.
print ("sample2:", np.mean(sample2.fare), st.norm.interval(alpha=0.95, loc=np.mean(sample2.fare), scale=st.sem(sample2.fare)))
print ("population:", np.mean(titanic.fare))
st.ttest_1samp(sample1.fare, 20)
from scipy.stats import chisquare
num_class=sample2["class"].value_counts()
print (num_class)
print (chisquare (num_class))