시험이 드디어 다 끝났다.
거지같던 프로젝트도 끝났다.
이제 다시 일상으로 돌아와야지...
사실 시리즈 자체를 공부해보려고 판다스 사이트를 들어갔었는데, 진짜 개많더라...
그래서 시리즈와 DF를 이리저리 변환해보고 바꿔보는 것만 해보겠다.
참고한 페이지는 하단 링크.
https://www.delftstack.com/ko/howto/python-pandas/convert-pandas-series-to-dataframe/
Pandas 시리즈를 DataFrame으로 변환
Pandas 시리즈를 데이터 프레임으로 변환하는 방법을 소개합니다.
www.delftstack.com
0. Make a data
우선 시리즈 데이터를 만들었다.
이때 사용한 것이 numpy.
seed를 고정해주기 위해 random seed=42로 정해주고, (국룰 42)
시리즈는 무조건 한줄로 이루어져 있어야되기 때문에 한줄의 숫자를 뽑아왔다.
import pandas as pd
import numpy as np
np.random.seed(42)
df_series = pd.Series(np.random.randint(0, 100, size=(5)), index=['가', '나', '다', '라', '마'])
df_series
<출력결과>
가 51
나 92
다 14
라 71
마 60
dtype: int32
여기서 잠깐, np.random.randint가 뭐지?
단어 그대로, random하게 integer를 뽑아오는 것이다.
ex) 0~100까지의 정수 중에 3개를 뽑아오자.
code> np.random.randint(0, 100, size=3)
result> 54, 63, 2
1. 단일 Pandas Series를Dataframe으로 변환
만든 series data를 dataframe으로 변환시키자.
이때 두가지 방식을 사용하는데, 첫째는 to_frame을 사용하는 것이다.
print(df_series.to_frame(name='num'))
print(type(df_series.to_frame(name='num')))
num
index
가 20
나 82
다 86
라 74
마 74
<class 'pandas.core.frame.DataFrame'>
시리즈 data 뒤에 .을 붙이고, to_frame을 사용해주었다.
여기서 중요한 건 DF로 바꿀 때, name을 설정해줘야 한다는 것이다.
name 안해주면 빈 DF이 나오더라...
name은 to_frame의 괄호 안에 적어주면 된다.
두번째 방법은... 사실 방법이라 하기 좀 뭐하다.
이건 index를 직접 열로 만들어줘서 ncol=2인 DF로 변환시키는 방식이다.
사용하는 코드는 rename_axis와 reset_index이다. 직접 코드로 확인하자.
1) reset_index : index를 DF로 빼준다.
df = pd.Series(np.random.randint(0, 100, size=(5)),
index=['가', '나', '다', '라', '마'])
print(df)
print(df.reset_index())
가 41
나 44
다 61
라 56
마 5
dtype: int32
index 0
0 가 41
1 나 44
2 다 61
3 라 56
4 마 5
원래 시리즈였던 data가,
reset_index를 사용해주며 Dataframe이 되었다.
즉 index도 하나의 column으로 바뀌며 DF에 들어오게 되는 것이다.
index 말고 다른 이름으로도 가능하다.
여기서 이제 rename_axis가 사용된다.
2) rename_axis : index의 이름을 지정해준다.
df = pd.Series(np.random.randint(0, 100, size=(5)),
index=['가', '나', '다', '라', '마']).rename_axis('한글')
print(df)
print(df.reset_index())
한글
가 68
나 97
다 69
라 85
마 10
dtype: int32
한글 0
0 가 68
1 나 97
2 다 69
3 라 85
4 마 10
index의 이름을 바꿔주고, 이걸 이제 reset_index를 이용해 DF로 만들어준 것이다.
그런데 막상 바꾸고 보니까 숫자들의 column name이 '0'인게 거슬리지 않은가?
그럼 reset_index에 있는 기능을 사용한다.
df = pd.Series(np.random.randint(0, 100, size=(5)),
index=['가', '나', '다', '라', '마']).rename_axis('한글')
df1 = df.reset_index(name="num")
df1
column 이름에 num이 생긴 것을 확인할 수 있다.
정리::
pd.Series data를 만들고, DF로 변환하고자 한다.
1. to_frame을 사용한다.
2. reset_index를 사용해 DF에 index를 포함시킨다.
2-1. reset_index(name='~')을 사용하면 Series data의 이름이 0이 아닌 다른 것으로 저장할 수 있다.
** 이때 rename_axis를 사용하면 index 이름 바꿀 수 있다.
2. 여러 Pandas Series를Dataframe으로 변환
Pandas의 concat 함수를 사용한다. 이때 axis를 1로 설정해줘야 한다는 사실을 잊지 말자.
df1 = pd.Series(np.random.randint(0,100,size=(5)),
index=['a', 'b', 'c', 'd', 'e'])
df2 = pd.Series(np.random.randint(40,100,size=(5)),
index=['a', 'b', 'c', 'd', 'e'])
df3 = pd.Series(np.random.randint(80,100,size=(5)),
index=['a', 'b', 'c', 'd', 'e'])
df = pd.concat([df1, df2, df3], axis=1)
0 1 2
a 88 85 95
b 98 57 88
c 24 41 83
d 92 93 80
e 17 74 83
막상 만들고 보니 열 이름이 0, 1, 2으로 되어있다.
거슬리니 rename 함수를 이용해 수정해주자.
df = df.rename(columns={0:'df1', 1:'df2', 2:'df3'})
print(df)
df1 df2 df3
a 88 85 95
b 98 57 88
c 24 41 83
d 92 93 80
e 17 74 83
go o o o o o d !
'PYTHON' 카테고리의 다른 글
NUMPY :: np.random (1) (0) | 2021.11.09 |
---|---|
PANDAS :: 인덱스 함수들 (reset_index, set_index, sort_index) (0) | 2021.11.08 |
PANDAS :: read_pickle (0) | 2021.10.20 |
PANDAS :: groupby() (0) | 2021.10.19 |
PANDAS :: read_csv (0) | 2021.10.19 |