240514 Today I Learn
๋ฐ์ดํฐ ๊ฒฐํฉํ๊ธฐ
Concat
๐ก Concat
ํ๋ค์ค ๊ฐ์ฒด๋ค์ ์์ง/ ์ํ์ผ๋ก ๋ถ์ด๊ธฐ
pd.concat(['๋ฐ์ดํฐํ๋ ์1','๋ฐ์ดํฐํ๋ ์2'], axis=0/1)โ
Merge
๐ก Merge
pd.merge(๋ฐ์ดํฐํ๋ ์1, ๋ฐ์ดํฐํ๋ ์2, on="๊ณตํต๋ ์ปฌ๋ผ", join = 'inner/outer/left/right/cross')
- ๊ณตํต๋ ์ปฌ๋ผ์ด ์๋ ๋ฐ์ดํฐํ๋ ์์ ํค๊ฐ์ ๊ธฐ์ค์ผ๋ก ํฉ์น๊ณ ์ ํ ๋ ์ฌ์ฉ ๊ฐ๋ฅ
- ํน์ ์ด์ ๋ฐ๋ผ SQL ์คํ์ผ์ ์กฐ์ธ์ ์ฌ์ฉํ ์ ์์
๐ SQL์ ์กฐ์ธ๊ณผ pandas Merge ํจ์์ ์กฐ์ธ ์ต์
Comparison with SQL — pandas 2.2.2 documentation
Comparison with SQL Since many potential pandas users have some familiarity with SQL, this page is meant to provide some examples of how various SQL operations would be performed using pandas. If you’re new to pandas, you might want to first read through
pandas.pydata.org
๊ทธ๋ฃนํํ๊ธฐ
๐ก ๊ทธ๋ฃนํ๋?
๋ค์์ ๋จ๊ณ ์ค ํ๋ ์ด์์ ํฌํจํ๋ ๊ณผ์ ์ด๋ค.
- ์ผ๋ถ ๊ธฐ์ค์ ๋ฐ๋ผ ๋ฐ์ดํฐ๋ฅผ ๊ทธ๋ฃน์ผ๋ก ๋ถํ
- ๊ฐ ๊ทธ๋ฃน์ ๋ ๋ฆฝ์ ์ผ๋ก ๊ธฐ๋ฅ์ ์ ์ฉ
- ๊ฒฐ๊ณผ๋ฅผ ๋ฐ์ดํฐ ๊ตฌ์กฐ๋ก ๊ฒฐํฉ
์ง๊ณํจ์์ ๊ทธ๋ฃนํ
- ์ง๊ณํจ์ sum์ ์ด์ฉํ ๊ทธ๋ฃนํ
df.groupby("A")[["C","D"]].sum()
→ 'A' ์ปฌ๋ผ์ ๊ฐ์ ๊ทธ๋ฃนํํด์ 'C', 'D'์ด์ ํฉ๊ณ๋ฅผ ๊ตฌํจ
- ์ฌ๋ฌ ์ด์ ๊ธฐ์ค์ผ๋ก ๊ทธ๋ฃนํ ํ ์ ์์
df.groupby(["A", "B"]).sum()
→ [๋ฆฌ์คํธ]์์ ์ ๋ ฅํ ์นผ๋ผ ์์๋๋ก ๊ทธ๋ฃนํ
ํผ๋ฒํ ์ด๋ธ
๐ก pd.pivot_table
pd.pivot_table(๋ฐ์ดํฐํ๋ ์, values = '๊ฐ์ด ๋ ์ปฌ๋ผ', index=['์ธ๋ฑ์ค ๊ฐ์ผ๋ก ์ง์ ํ ์ปฌ๋ผ'], columns= ['์ปฌ๋ผ์ ๋ค์ด๊ฐ ๊ฐ'])
pd.pivot_table(df, values="D", index=["A","C"], columns=["B"])