[Python] map, apply, applymap
map()
mapํจ์๋ DataFrame์ Seriesํ์ ์ Input์ผ๋ก ๋ฐ์ต๋๋ค.
๋ฐ๋ผ์ mapํจ์๋ฅผ ์ด์ฉํ๋ฉด Series๋ฅผ ๋์์ผ๋ก ์ํ๋ ํจ์๋ฅผ ์ ์ฉํ ์ ์์ต๋๋ค.
In [1]:
import pandas as pd
In [2]:
df = pd.DataFrame({"age":[30,25,25,12,40],
"height":[178,180,160,140,176],
"weight":[80,100,55,40,70]})
df
Out[2]:
ageheightweight01234
30 | 178 | 80 |
---|---|---|
25 | 180 | 100 |
25 | 160 | 55 |
12 | 140 | 40 |
40 | 176 | 70 |
In [4]:
df['weight(pound)'] = df['weight'].map(lambda x: x*2.205)
df
Out[4]:
ageheightweightweight(pound)01234
30 | 178 | 80 | 176.400 |
---|---|---|---|
25 | 180 | 100 | 220.500 |
25 | 160 | 55 | 121.275 |
12 | 140 | 40 | 88.200 |
40 | 176 | 70 | 154.350 |
์์ฒ๋ผ lambda ํจ์๋ฅผ ์ด์ฉํด ํน์ ์๋ฆฌ์ฆ(์ปฌ๋ผ)์ ๋ํด ์ํ๋ ํจ์๋ฅผ ์ ์ฉํด ์๋ก์ด ์ปฌ๋ผ์ ์์ฑํ ์ ์์ต๋๋ค.
apply()
apply ํจ์๋ mapํจ์์ ๋ค๋ฅด๊ฒ ์ ์ฒด Series(์ปฌ๋ผ)๋ฅผ ๋์์ผ๋ก ์ํ๋ ํจ์๋ฅผ ์ ์ฉํฉ๋๋ค.
In [5]:
df.apply(lambda x: x.max()-x.min())
Out[5]:
age 28.0
height 40.0
weight 60.0
weight(pound) 132.3
dtype: float64
์์ ๊ฒฐ๊ณผ๋ฅผ ๋ณด๋ฉด ์ ์ ์๋ฏ์ด ์ ์ฒด ์ปฌ๋ผ์ ๋ํ์ฌ ์ต๋๊ฐ - ์ต์๊ฐ์ ๊ตฌํ๋ ํจ์๋ฅผ ์ ์ฉํ์ต๋๋ค.
์ด๋ฅผ ์ด์ฉํ๋ฉด ์ ์ฒด ์ปฌ๋ผ์ ๋ํด ํน์ ํจ์๋ฅผ ์ ์ฉํด ๋น ๋ฅธ Summary๊ฐ ๊ฐ๋ฅํ๋ค๋ ์ฅ์ ์ด ์์ต๋๋ค.
์ถ๊ฐ์ ์ผ๋ก applyํจ์๋ axis ์ธ์๋ฅผ ์ด์ฉํ์ฌ ์ํ๋ ์ถ ๋ฐฉํฅ์ ๋ฐ๋ผ ํจ์๋ฅผ ์ ์ฉํ ์ ์์ต๋๋ค.
In [6]:
df.apply(sum, axis=0) # axis=0 ์ ๋ํดํธ(), ํ๋ฐฉํฅ
Out[6]:
age 132.000
height 834.000
weight 345.000
weight(pound) 760.725
dtype: float64
In [7]:
df.apply(sum, axis=1) # ์ด๋ฐฉํฅ
Out[7]:
0 464.400
1 525.500
2 361.275
3 280.200
4 440.350
dtype: float64
applymap()
applymap ํจ์๋ DataFrame์ ๋ชจ๋ element์ ๋ํด ์ํ๋ ํจ์๋ฅผ ์ ์ฉํฉ๋๋ค. ๋ฐ๋ผ์ axis์ ๊ฐ์ ์ธ์๋ ์ฌ์ฉ๋์ง ์์ต๋๋ค.
In [9]:
df.applymap(lambda x:-x)
Out[9]:
ageheightweightweight(pound)01234
-30 | -178 | -80 | -176.400 |
---|---|---|---|
-25 | -180 | -100 | -220.500 |
-25 | -160 | -55 | -121.275 |
-12 | -140 | -40 | -88.200 |
-40 | -176 | -70 | -154.350 |
In [ ]: