출처: http://stackoverflow.com/questions/12190874/pandas-sampling-a-dataframe
Pandas에서 random sampling 할 수 있도록 함수 제공
- sample 함수이용
- df.sample(n=몇개의 row를 샘플할 것인지/sample 갯수 값)
출처: http://stackoverflow.com/questions/12190874/pandas-sampling-a-dataframe
Pandas에서 random sampling 할 수 있도록 함수 제공
- sample 함수이용
- df.sample(n=몇개의 row를 샘플할 것인지/sample 갯수 값)
출처: http://stackoverflow.com/questions/22019763/pandas-writing-dataframe-columns-to-csv
header = ["Time", "User", "IP Address"] df.to_csv('output.csv', columns = header) |
- header라는 변수에 export하고 싶은 컬럼을 적어주면 원하는 컬럼만 csv로 export 할 수 있음
출처 : https://www.dezyre.com/data-science-in-r-programming-tutorial/k-means-clustering-techniques-tutorial
- wss
출처: https://datasciencelab.wordpress.com/2013/12/12/clustering-with-k-means-in-python/
- 파이썬으로 구현한 k-means
출처: http://scikit-learn.org/stable/modules/generated/sklearn.cluster.KMeans.html
- scikit에서의 k-means 설명
출처: https://www.packtpub.com/books/content/k-means-clustering
- R에서 wssplot 그리는 것
출처: http://stackoverflow.com/questions/3061761/numpy-array-dimensions
.shape()
- shape함수를 사용하면 데이터 구조 확인 가능
(행렬 정보)
출처: http://stackoverflow.com/questions/24493918/pandas-set-cell-format-in-excel-writer
import pandas as pd .... writer = pd.ExcelWriter('test.xlsx') df1.to_excel(writer, 'Sheet1') df2.to_excel(writer, 'Sheet2') writer.save() .... |
- pd.ExcelWriter로 저장할 엑셀 파일 객체 생성
- 해당 객체에 dataframe값을 to_excel 함수를 이용해서 내보냄 with 시트명
출처: http://stackoverflow.com/questions/10715965/add-one-row-in-a-pandas-dataframe
Pandas에서 새로운 데이터 프레임 생성하고 값을 추가할 때
df = DataFrame(columns=('number', 'name')) df.loc[0] = [1, '박명수'] df.loc[1] = [2, '유재석'] ... |
데이터 프레임에 컬럼을 추가해주고, 해당 데이터를 loc 함수를 이용해서 넣어주면 됨
출처: http://stackoverflow.com/questions/1985856/how-to-make-a-3d-scatter-plot-in-python
import matplotlib.pyplot as plt import pylab from mpl_toolkits.mplot3d import Axes3D fig = pylab.figure() ax = Axes3D(fig) qid = grouped.query('(user_number == 123)') x = qid['loc_x'].tolist() y = qid['loc_y'].tolist() xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) ax.scatter(x, y, z) plt.show() |
- gaussian_kde를 이용해서 z 축은 확률밀도 값으로 출력
출처: http://pandas.pydata.org/pandas-docs/stable/groupby.html
grouped.size()
- 그룹된 결과에 size()함수를 사용하면 그룹에 속한 갯수를 확인할 수 있음
grouped.reset_index()
- group된 dataframe 타입에서 dataframe 타입으로 변경할 수 있음
grouped['user_name'].apply(lambda x: ', '.join(str(y) for y in x))
- user_name이라는 컬럼의 값이 리스트인 경우 스트링의 연결로 변경해줌
- apply와 lambda함수 사용
for c in grouped.groups :
print c
- 그룹 명을 출력할 때 사용
출처: http://stackoverflow.com/questions/20105364/how-can-i-make-a-scatter-plot-colored-by-density-in-matplotlib
python matplotlib를 이용해서 scatter plot을 그리는 데 밀도도 반영하고 싶다면 아래와 같이 하면 됨
import numpy as np import matplotlib.pyplot as plt from scipy.stats import gaussian_kde # 출력할 x,y 좌표 랜덤하게 생성 x = np.random.normal(size=1000) y = x * 3 + np.random.normal(size=1000) # 좌표에 대한 밀도를 계산하는 부분 xy = np.vstack([x,y]) z = gaussian_kde(xy)(xy) fig, ax = plt.subplots() #색깔은 z에 따라서, 점의 크기는 100으로 ax.scatter(x, y, c=z, s=100, edgecolor='') plt.show() |
참고: http://stackoverflow.com/questions/24976239/axis-limits-for-scatter-plot-matplotlib
plt.xlim(-1,1) plt.ylim(-1,1) |
- 이용해서 축의 범위를 정할 수 있음 (추후 확인해보기!)
참고: http://stackoverflow.com/questions/9622163/save-plot-to-image-file-instead-of-displaying-it-using-matplotlib-so-it-can-be
fig.savefig('/path/image.png') |
- plot 결과를 이미지 파일로 저장할 수 있음
출처 : http://blog.bharatbhole.com/creating-boxplots-with-matplotlib/
- python에서 boxplot 그리기
출처: http://chrisalbon.com/python/pandas_join_merge_dataframe.html
Pandas에서 두 Dataframe을 합치기 위해서는
pd.merge(df1, df2, on="user_name", how="inner") |
사용해보니 SQL에 inner join과 같아서 좋음