기본 콘텐츠로 건너뛰기

Python Pandas

import pandas as pd

Series
dict = {'a':1,'b':2,'c':3}
pd.Series(dict)
pd.Series(['Dog','Cat','Tiger','Lion','Monkey'])

DataFrame
dict = {'동물':['Dog','Cat','Tiger','Lion','Monkey'],'나이':[7,9,2,3,1]}
df = pd.DataFrame(dict)

예제
딕셔너리
dict = {'1분기':['1-1','1-2','1-3','1-4','1-5'],'2분기':['2-1','2-2','2-3','2-4','2-5'],'3분기':['3-1','3-2','3-3','3-4','3-5'],'4분기':['4-1','4-2','4-3','4-4','4-5']}
pd.DataFrame(dict,index=['dept1','dept2','dept3','dept4','dept5'])
##
1분기 2분기 3분기 4분기
dept1 1-1 2-1 3-1 4-1
dept2 1-2 2-2 3-2 4-2
dept3 1-3 2-3 3-3 4-3
dept4 1-4 2-4 3-4 4-4
dept5 1-5 2-5 3-5 4-5

리스트
list = [['1-1','1-2','1-3','1-4'],['2-1','2-2','2-3','2-4'],['3-1','3-2','3-3','3-4'],['4-1','4-2','4-3','4-4'],['5-1','5-2','5-3','5-4']]
pd.DataFrame(list,index=['dept1','dept2','dept3','dept4','dept5'],columns=['1분기','2분기','3분기','4분기'])
##
1분기 2분기 3분기 4분기
dept1 1-1 1-2 1-3 1-4
dept2 2-1 2-2 2-3 2-4
dept3 3-1 3-2 3-3 3-4
dept4 4-1 4-2 4-3 4-4
dept5 5-1 5-2 5-3 5-4

첫번째 행부터 가져오기
df_emps.head(3) # 앞에서 3개 가져온다

마지막 행부터 가져오기
df_emps.tail(7) # 뒤에서 7개 가져온다

특정 컬럼 Series 로 가져오기
ser_first_name = df_emps['first_name']

Series를 Numpy로 변환하기
ser_first_name.to_numpy()

특정 행 선택할 때 주의사항
#df_emps[3] # 3번행을 가져올 수는 없다. DF 참조에서 []를 이용하면 컬럼만 선택가능

행 가져오기
df_emps['phone'][:10] # 10개의 행 가져온다

순번으로 정한 인덱스로 검색
df_emps.loc[3] # Series

인덱스 번호로 검색
df_emps.iloc[3]

Series에서 Index 번호로 특정 행 찾기
ser_first_name[1] # 'Douglas'

다수개의 행, 특정 순번 가져오기
df_emps[['first_name','phone']].loc[2:5] # DataFrame으로 반환한다

순서 없이 다수개의 행을 가져오기
df_emps.loc[[1,3,5]]

인덱스 번호로 순서 없이 다수개의 행을 가져오기
df_emps.iloc[[1,3,5]]

열 제거
df_row3.drop('gender',axis=1) # axis : 0(행 한개 지우기), 1(열 한개 지우기), 사본의 gender 열이 사라짐

특정 행에서 특정 열을 가져오기
# 인덱서 안에서 쉼표는 행과 열의 의미이다.
df_emps.iloc[3,1] # 'Charles'
df_emps.iloc[3]['first_name'] # 'Charles'

특정 다수의 행에서 특정 열을 가져오기
df_emps.iloc[[1,2],[0,1]] # index 1번,2번 행의 0번 열('gender'), 1번 열('first_name')을 가져온다

특정 행 중에서 조건을 만족하는 열
df_row3[df_row3['first_name']=='Jose']

DataFrame 쉽고 빠르게 만들기
pd.DataFrame(np.arange(12).reshape(3,4),index={'a','b','c'},columns={'가','나','다','라'})
##
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11

pd.DataFrame(np.arange(12).reshape(3,4),index={'a','b','c'},columns=['가','나','다','라'])
##
a 0 1 2 3
b 4 5 6 7
c 8 9 10 11

JSON 문자열을 DataFrame으로 변환하기
# json 사이트에서 json 데이터를 가져와서, 그 중에 employees 키에 값으로 등록된 리스트를
# 추출하여 딕셔너리로 변환하고, 결국에는 dataFrame에 표시되도록 해보세요.
# https;//api.slingacademy.com/v1/sample-data/files/employees.json
import requests
res = requests.get("https://api.slingacademy.com/v1/sample-data/files/employees.json")
res.status_code

import json
json = json.loads(res.text)
list_employees = json['employees']
type(list_employees)

import pandas as pd
df = pd.DataFrame(list_employees)

원본 열 삭제
.drop(4,axis=1,inplace=True)

행의 열 갯수 구하기
df.count()
##
0      4
1      4
2      4
3      4
sum    4
4      4
dtype: int64

인덱스 구하기
.index[0] # 0번 방의 인덱스 구하기
.index[-1] # 마지막 행의 인덱스를 구하기

열 이름 변경
df.columns = ['1월','2월','3월','4월','합계']

각 열에 대한 행의 합
df.sum(axis=0) # 각 열에 대한 행의 합
##
0       24
1       28
2       32
3       36
sum    120
dtype: int64

각 행에 대한 열의 합
df.sum(axis=1)
##
0     12
1     44
2     76
3    108
dtype: int64

인덱스 오름차순으로 행들을 정렬
df.sort_index()
df_reverse = df.sort_index(ascending=False)
##
        0 1 2 3 sum
3 12 13 14 15 54
2 8 9 10 11 38
1 4 5 6 7 22
0 0 1 2 3 6

정렬
df_reverse.sort_values(by='sum')
##
        0 1 2 3 sum
0 0 1 2 3 6
1 4 5 6 7 22
2 8 9 10 11 38
3 12 13 14 15 54

열 추가
df[4] = [0,0,0,0]

행 추가
df.loc[4] = [0,0,0,0,0]

열 읽어오기
df[4]

행 읽어오기
df[[4]]

인덱스로 행 읽어오기
df.loc[1]

중복없이 인덱스로 행 읽어오기
df.iloc[0]
df.iloc[0,0] # 0번 인덱스의 0번째 값

열 삭제, 한 행 삭제
members.drop(0,axis=0,inplace=True) # 0 인덱스의 한 열 삭제

행 삭제, 한 열 삭제
members.drop('rating',axis=1,inplace=True) # 0 열의 한 행 삭제

셀 삭제
df[1][0] = np.nan # NaN, 1번째 열의 0번째 행 값을 삭제

셀 값 변경
df[df!=0] = 0 # 0이 아닌 셀을 모두 0으로 변경

CSV 파일로 저장하기
dtypes = {'이름': str,'나이': int,'성별': 'category'}
df.to_csv('sample_df.csv',index=False,encoding="euc-kr",dtype=dtypes) # index=False는 인덱스를 저장하지 않음

csv 파일을 DataFrame으로 변환
df_emps = pd.read_csv('employees.csv',header=None,index_col=0,names=['gender','first_name','phone','job_title']) # index_col[위치/아이디] : index로 지정할 컬럼

isnull
df.isnull()
df[df.isnull()] = 0.0 # null인 셀에 0.0을 대입

notnull
df.notnull()
df[df.notnull()] = 0 # null이 아닌 셀에 0을 대입

dropna
df.dropna(axis=0, inplace=True) # 값을 갖지 않는(Nan) 행을 제거한다
df.dropna(axis=1, inplace=True) # 값을 갖지 않는(Nan) 열을 제거한다

데이터 타입 알아내기
df.dtypes

데이터 타입 변경
df  = df.astype(int)

null 인 곳에 값을 채우기
df.fillna(10) # null인 곳에 10을 채움
df.fillna(df.mean()) # null인 곳에 각 열의 평균을 채움

모든 셀에 대해서 반복하기
mean = df.mean()
df.apply(lambda c : c.fillna(c.mean()), axis=0) # null인 곳에 각 행의 평균을 채움

중복 검사
df.duplicated()

예제
# 1 ~ 5 사이의 정수 15개를 추출하여 5x3 행렬 생성
# df에 중복된 값이 있는지 확인해보세요.
df = pd.DataFrame(np.random.randint(1,5+1,30).reshape(10,3))
df
##
0 1 2
0 1 3 5
1 1 4 3
2 4 2 4
3 4 1 4
4 1 3 5
5 1 1 5
6 3 5 1
7 4 1 4
8 3 1 4
9 4 2 4

df.duplicated([0], keep='first') # 0열의 중복 값이 있을 경우 True
##
0    False
1     True
2    False
3     True
4     True
5     True
6    False
7     True
8     True
9     True
dtype: bool

df.duplicated([0,1,2], keep='first') # 0열과 그 행의 중복 값이 있을 경우 True
##
0    False
1    False
2    False
3    False
4     True
5    False
6    False
7     True
8    False
9     True
dtype: bool

group by
group_info = df.groupby([0])
group_info.groups # {1: [0, 1, 4, 5], 3: [6, 8], 4: [2, 3, 7, 9]}
g1 = group_info.get_group(1) # 0열에서 1이 있는 행들
type(g1) # pandas.core.frame.DataFrame
group_info.get_group(1).sum()
'''
0     4
1    11
2    18
dtype: int64
'''

예제
# 성적 테이블 작성
# 컬럼 : 국어, 영어, 국사, 
# 점수 : 1~5
# 학생 20명의 성적
df = pd.DataFrame(np.random.randint(1,6,60).reshape(20,3),columns=['국어','영어','국사'])
g = df.groupby(['국어'])
display(list(g))
'''
[(1,
     국어  영어  국사
  2   1   3   5
  3   1   3   3
  4   1   2   3),
 (2,
      국어  영어  국사
  0    2   2   3
  7    2   4   3
  10   2   2   5
  12   2   2   2),
 (3,
      국어  영어  국사
  1    3   1   5
  6    3   5   1
  8    3   2   3
  11   3   3   2
  14   3   2   1
  17   3   1   2
  18   3   5   5
  19   3   5   4),
 (4,
      국어  영어  국사
  16   4   1   5),
 (5,
      국어  영어  국사
  5    5   5   2
  9    5   3   3
  13   5   3   2
  15   5   3   4)]
'''
g.get_group(1)['국어'].count() # 3, 국어가 1인 그룹의 수
g.get_group(2)['국어'].count() # 4
g.get_group(3)['국어'].count() # 8
g.get_group(4)['국어'].count() # 1
g.get_group(5)['국어'].count() # 4

# 반별로 국어 평균 출력
g = df.groupby(['반'])
g['국어'].mean()
'''
1    3.076923
2    2.714286
Name: 국어, dtype: float64
'''
# 반별로 국어 평균, 최소, 최고
g['국어'].agg(['mean','min','max'])
'''
  mean     min max
1 3.076923 1   5
2 2.714286 1   5
'''

cut
예제
rg = np.arange(1,11)
ct = pd.cut(rg,3)
'''
[(0.991, 4.0], (0.991, 4.0], (0.991, 4.0], (0.991, 4.0], (4.0, 7.0], (4.0, 7.0], (4.0, 7.0], (7.0, 10.0], (7.0, 10.0], (7.0, 10.0]]
Categories (3, interval[float64, right]): [(0.991, 4.0] < (4.0, 7.0] < (7.0, 10.0]]
# (0.991, 4.0]
# 0.991를 포함하지 않고, 4.0을 포함한 범위
# (4.0, 7.0]
# 4.0를 포함하지 않고, 7.0을 포함한 범위
# (7.0, 10.0]
# 7.0를 포함하지 않고, 10.0을 포함한 범위
'''

Categories
ct.categories[0] # Interval(0.991, 4.0, closed='right'), closed는 포함이 되어있다는 뜻, 오른쪽이 포함된 범위

왼쪽과 오른쪽 값 추출
ct.categories[0].left, ct.categories[0].right # (0.991, 4.0)

왼쪽과 오른쪽의 포함 범위 알아내기
ct.categories[0].open_left, ct.categories[0].closed_right # (True, True)

# 위에서 나눈 범주 3개를 a, b, c 라고 이름을 붙인다면,
# 각 범주에 속하는 값들을 화면에 표시해보세요
list_ct = list(ct.categories)
'''
[Interval(0.991, 4.0, closed='right'),
 Interval(4.0, 7.0, closed='right'),
 Interval(7.0, 10.0, closed='right')]
'''
for i, ct in enumerate(list_ct):
    print(i,",")
    print(*list(item for item in rg if ct.left < item and item <= ct.right))
'''
0 ,
1 2 3 4
1 ,
5 6 7
2 ,
8 9 10
'''

qcut
pd.qcut(np.arange(1,11),3)
'''
[(0.999, 4.0], (0.999, 4.0], (0.999, 4.0], (0.999, 4.0], (4.0, 7.0], (4.0, 7.0], (4.0, 7.0], (7.0, 10.0], (7.0, 10.0], (7.0, 10.0]]
Categories (3, interval[float64, right]): [(0.999, 4.0] < (4.0, 7.0] < (7.0, 10.0]]
'''

이 블로그의 인기 게시물

Blogger

코드 하이라이트 사이트 http://hilite.me/ 코드 <!-- 나만의 공간 --> <style id='daru_css' type='text/css'> .code {      overflow: auto;      height: 200px;      background-color: rgb(239,239,239);      border-radius: 10px;      padding: 5px 10px; } .code::-webkit-scrollbar-thumb {      background-color: grey;      border: 1px solid transparent;      border-radius: 10px;      background-clip: padding-box;   } .code::-webkit-scrollbar {      width: 15px; } </style> <!-- 나만의 공간 -->

Python 인공신경망 추천 시스템(회귀)

예제 # 인공신경망을 이용한 추천 시스템 # - 순차형(Sequential) 신경망 생성법 # - 함수형(Functional) 신경망 생성법 # - 지금까지 나온 추천 방식 중에서 가장 좋은 성능 # - Regression 방식으로 분석가능 # - 영화의 평점 정보(userid, movieid, rating) # - 이용자는 영화에 대한 취향이 모두 다르다 # - 영화는 다양한 장르가 혼합되어 있다 # - 이용자는 자신의 취향에 맞는 영화에 높은 rating을 제시함 # - 어떤 이용자에게 어떤 장르의 영화를 추천할 것인가? # __call__() 함수를 가진 클래스는 파이썬 함수 callable(클래스)를 사용하면 True를 반환한다 from tensorflow.keras.models import Sequential, Model from tensorflow.keras.layers import Dense, Embedding, Input input = Input(shape=(1,)) # 함수형 신경망 생성법 hidden1 = Dense(2, activation='relu')(input) # Dense(2, activation='relu')__call__() hidden2 = Dense(2, activation='relu')(hidden1) # callable.object callable(Dense) # __call__ 함수가 있으면 True, 없으면 False # Using Functional API from keras.models import Sequential from keras.layers import * model = Sequential() model.add(Input(shape=(3,))) # Input tensor model.add(Dense(4)) # hidden layer 1 model.add(Dense(units=4)) # hidden layer 2 model.add(Dense(units=1)) # ou...

Python 문법

제곱 c = c**2; 주석 # 주석 함수 # 함수 형식 def hello(): # 함수 선언     print("여기는 함수") # 함수 실행문 hello() # 함수 호출 #결과: 여기는 함수 def add(a,b): # 매개변수에 자료형이 필요없다     c = a+b     print(f"{a} + {b} = {c}") add(3,5) #결과 : 3 + 5 = 8 if문 if a > b:     print("a가 큽니다") 객체의 정보 dir(객체) 객체의 주소 id(객체) 생략 if 'a' == 'a':     pass # 생략 else:     pass # 생략 enumerate for i,v in enumerate(range(20, 26)):     print(i,v) display display(df)