๋ ์ฝ๋, ์นผ๋ผ ์ถ๊ฐ / ์ญ์
import pandas as pd
df = pd.DataFrame({'a' : [1, 1, 3, 4, 5], 'b' : [2, 3, 2, 3, 4], 'c' : [3, 4, 7, 6, 4]})
df
1. ์นผ๋ผ(column) ์ถ๊ฐ
- [] ์ฐ์ฐ์๋ฅผ ์ฌ์ฉํ์ฌ ๊ธฐ์กด DataFrame์ ์ ์ด ์ถ๊ฐ ํ ์ ์๋ค
-๋ฌธ์ : 1, 3, 6, 4. 8 ๋ก ์ด๋ฃจ์ด์ง d ์นผ๋ผ์ ์ถ๊ฐํ๊ธฐ
df['d'] = [1, 3, 6, 4, 8]
df
-๋ฌธ์ : 1๋ก ์ด๋ฃจ์ด์ง e ์นผ๋ผ ์ถ๊ฐํ๊ธฐ
df['e'] = [1, 1, 1, 1, 1]
df
์ด๋ ๊ฒ ํ๋ ๋ฐฉ๋ฒ๋ ์์ง๋ง ์กฐ๊ธ ๋ ์ฝ๊ฒ ํ๋ ๋ฐฉ๋ฒ์ด ์๋ค.
df['e'] = 1
df
df.dtypes
a int64
b int64
c int64
d int64
e int64
dtype: object
-๋ฌธ์ : a + b - c ์ ๊ฒฐ๊ณผ๋ก ์ด๋ฃจ์ด์ง f ์นผ๋ผ์ ์ถ๊ฐํ๊ธฐ
df['f'] = df['a'] + df['b'] - df['c']
df
2. ์นผ๋ผ (column) ์ญ์
- drop(labels) : DataFrame ์ด ์ญ์
-๋ฌธ์ : ์นผ๋ผ d, e, f ๋ฅผ ์ญ์ ํ๊ธฐ
df.drop(['d', 'e', 'f'], axis=1)
df
df.drop(['d', 'e', 'f'], axis=1, inplace=True)
df
3. ๋ ์ฝ๋ ์ถ๊ฐ
- append() : ์ฌ์ ์ ๊ฐ์ ํ์ผ๋ก ์ง์ ๊ฐ์ง๊ณ ์์ DataFrame์ ์ถ๊ฐ
-๋ฌธ์ : a์๋ 6, b์๋ 7, c์๋ 8์ ์ถ๊ฐํ๊ธฐ
df.append({'a' : 6, 'b' : 7, 'c' : 8})
- ignore_index = True : ๊ธฐ์กด index๋ฅผ ๋ฌด์ํ๊ณ ์ถ์ ๋ , DataFrame์ ํฉ์น ๋ ignore_index๋ฅผ ํ์ง ์์ผ๋ฉด ๋ฐ์ดํฐ์ ์๋ ์ธ๋ฑ์ค๋ฅผ ๊ทธ๋๋ก ๊ฐ์ง๊ณ ์ด
df.append({'a' : 6, 'b' : 7, 'c' : 8}, ignore_index = True)
df
df = df.append({'a' : 6, 'b' : 7, 'c' : 8}, ignore_index = True)
df
- loc[index] : ๋ชฉ๋ก์ด ์๋ ๋ฐ์ดํฐ ํ๋ ์์ ํ์ ์ถ๊ฐ
-๋ฌธ์ : a์๋ 7, b์๋ 8, c์๋ 9๋ฅผ ์ถ๊ฐํ๊ธฐ
df.loc[6] = [7, 8, 9]
df
๋๊ธ