pandas IV¶
Pivot Table¶
- Index 축은 groupby와 동일함
- Column에 추가로 labeling 값을 추가하여,
Value에 numeric type값을 aggregation 하는 형태
In [1]:
import pandas as pd
import numpy as np
In [2]:
df_phone = pd.read_csv("./data/phone_data.csv")
df_phone.head()
Out[2]:
In [3]:
df_phone.pivot_table(values=["duration"],index=['month', 'item'],
columns='network',aggfunc="sum",fill_value=0)
Out[3]:
values
: 값을 나타낼 컬럼index
: 인덱스로 사용할 컬럼들 groupby되는 컬럼이라고 생각하면 편하다columns
:index
로 groupby되고 나온 DataFrame에서의 column을 선택하는 값. 이 값이 헷갈릴 수 있는데index
로 grouped된 DataFrame에 대해서 해당columns
의 인자로 다시 groupby을 한다고 생각하면 편하다.aggfunc
: 해당 값의 집계함수
In [4]:
df_phone.pivot_table(values=["duration"],
index='network',
columns='network_type',
aggfunc="first",
fill_value=0)
Out[4]:
Merge & Concat¶
두 DataFrame의 column이 다르다면 다음과 같이 설정을 해줘야 한다.
join method¶
In [5]:
raw_data = {
"subject_id": ["1", "2", "3", "4", "5"],
"first_name": ["Alex", "Amy", "Allen", "Alice", "Ayoung"],
"last_name": ["Anderson", "Ackerman", "Ali", "Aoni", "Atiches"],
}
df_a = pd.DataFrame(raw_data, columns=["subject_id", "first_name", "last_name"])
df_a
Out[5]:
In [6]:
raw_data = {
"subject_id": ["4", "5", "6", "7", "8"],
"first_name": ["Billy", "Brian", "Bran", "Bryce", "Betty"],
"last_name": ["Bonder", "Black", "Balwner", "Brice", "Btisan"],
}
df_b = pd.DataFrame(raw_data, columns=["subject_id", "first_name", "last_name"])
df_b
Out[6]:
left join¶
In [7]:
pd.merge(df_a, df_b, on="subject_id", how="left")
Out[7]:
right join¶
In [8]:
pd.merge(df_a, df_b, on="subject_id", how="right")
Out[8]:
full(outer) join¶
In [9]:
pd.merge(df_a, df_b, on="subject_id", how="outer")
Out[9]:
In [10]:
pd.merge(df_a, df_b, on="subject_id", how="inner")
Out[10]:
In [11]:
pd.merge(df_a, df_b, right_index=True, left_index=True)
Out[11]:
In [12]:
df_b.append([1,2,3])
Out[12]:
In [13]:
display(df_a)
display(df_b)
세로로 붙이기¶
In [14]:
df_new = pd.concat([df_a, df_b])
df_new
Out[14]:
In [15]:
df_a.append(df_b)
Out[15]:
- 이때 주의할 점은 열의 개수가 맞아야 한다.
가로로 붙이기¶
In [16]:
df_new = pd.concat([df_a, df_b], axis=1)
df_new
Out[16]:
- 이때 주의 할 점은 행의 개수가 맞아야 한다.
persistence¶
XLS persistence¶
- Dataframe의 엑셀 추출 코드
- Xls엔진으로 openpyxls또는 XlsxWrite 사용
- conda install openpyxl
- conda install XlsxWriter
- https://xlsxwriter.readthedocs.io/working_with_pandas.html
In [17]:
df = pd.DataFrame({'Data': [10, 20, 30, 20, 15, 30, 45]})
writer = pd.ExcelWriter('./data/pandas_simple.xlsx', engine='xlsxwriter')
df.to_excel(writer, sheet_name='Sheet1')
# Close the Pandas Excel writer and output the Excel file.
writer.save()
In [18]:
# DataFrame 저장
df.to_pickle("./data/df.pickle")
In [19]:
del df
In [20]:
df_pickle=pd.read_pickle("./data/df.pickle")
df_pickle
Out[20]:
'AI > 이론' 카테고리의 다른 글
seaborn (0) | 2021.01.29 |
---|---|
matplotlib II (0) | 2021.01.29 |
matplotlib I (0) | 2021.01.29 |
확률론 맛보기 (0) | 2021.01.28 |
Pandas III (0) | 2021.01.28 |
딥러닝 학습방법 이해하기 (0) | 2021.01.27 |
Pandas II (0) | 2021.01.27 |
Pandas I (0) | 2021.01.27 |