본문 바로가기
Python/Pandas

[Pandas] 판다스 기본 함수들

by 인사이티드 2023. 2. 3.

판다스에는 Series와 Dataframe에 모두 적용되는 기본 함수들이 있다.

1. head() & tail()

head와 tail 메서드는 샘플을 뽑아 보여주는 쉬운 메서드이다. head()는 앞에서부터 n개만큼의 샘플을, tail()은 뒤에서부터 n개만큼의 샘플을 보여준다. 매개변수를 전달하지 않는다면 default 값은 5개이다.
다음은 head()와 tail()의 예시이다.

d = {"one": range(20), "two": np.random.randn(20)}
df = pd.DataFrame(d)

df.head()
=>
	one	two
0	0	-0.262533
1	1	1.097868
2	2	0.627424
3	3	-0.150713
4	4	-0.656796

df.tail(1)
=>
    one	two
19	19	-1.397153


2. shape, index, columns

shape는 Series와 Dataframe에 달려있는 속성이다. 크기를 보여준다.

df.shape
=>
(20, 2)

Series는 index 속성을, Dataframe은 index와 columns 속성을 가지고 있다.

3. copy()

copy는 복사하는 메서드이다. copy 메서드는 깊은 복사를 수행하기 때문에 서로 독립적인 메모리를 가진다.

df1 = df.copy()


4. 기본적인 통계 함수

판다스는 넘파이처럼 기본적인 통계 함수를 제공한다.

count Number of non-NA observations
sum Sum of values
mean Mean of values
mad Mean absolute deviation
median Arithmetic median of values
min Minimum
max Maximum
mode Mode
abs Absolute Value
prod Product of values
std Bessel-corrected sample standard deviation
var Unbiased variance
sem Standard error of the mean
skew Sample skewness (3rd moment)
kurt Sample kurtosis (4th moment)
quantile Sample quantile (value at %)
cumsum Cumulative sum
cumprod Cumulative product
cummax Cumulative maximum
cummin Cumulative minimum


5. describe()

describe() 메서드는 기초통계량을 요약해주는 유용한 메서드이다.

df.describe()
=>
	one	two
count	20.00000 20.000000
mean	9.50000	-0.136238
std	5.91608	1.089613
min	0.00000	-2.063035
25%	4.75000	-0.778026
50%	9.50000	-0.188433
75%	14.25000 0.691383
max	19.00000 1.587672

 

6. value_counts(), mode()

value_counts() 메서드는 각 값들의 갯수를 알려주는 유용한 메서드이다. normalize=True를 통해 비율로 볼 수도 있다.

df2 = pd.DataFrame({'first':[2,2,2,2,4,4,6,6,6,6,6,6,10],
       'second':['one','one','one','two','two','three',
       		'three','three','three','three','four','four','four']})
df2.value_counts()
=>
first  second
6      three     4
2      one       3
6      four      2
2      two       1
4      three     1
       two       1
10     four      1
dtype: int64

mode() 메서드는 최빈값을 알려주는 메서드이다.

df2.mode()
=>
	first	second
0	6	three


7. apply()

apply() 메서드는 Dataframe에서 주로 쓰이는 함수이다. axis 파라미터를 0 또는 1로 설정해서 각 열 별로, 또는 행 별로 함수를 적용 가능하다. 기본값은 axis=0이다.

df.apply(np.mean)
=>
one    9.500000
two   -0.136238
dtype: float64

  
8. fillna()

fillna() 메서드는 null 값을 채워주는 메서드이다. 데이터분석 시 Dataframe에 결측치가 있는 경우가 많은데 그럴때 결측치를 채워줄 수 있는 유용한 메서드이다.

d = {
    "one": pd.Series([1.0, 2.0, 3.0], index=["a", "b", "c"]),
    "two": pd.Series([1.0, 2.0, 3.0, 4.0], index=["a", "b", "c", "d"]),
}
df = pd.DataFrame(d)

df.fillna(0)
=>
	one	two
a	1.0	1.0
b	2.0	2.0
c	3.0	3.0
d	0.0	4.0


9. drop()

drop() 메서드는 axis에 따라 열 또는 행을 없애는 메서드이다.

df.drop('one', axis=1)	# column 'one'을 없앤다.
=>
	two
a	1.0
b	2.0
c	3.0
d	4.0

axis 대신 columns 또는 index로 drop()을 실행할 수도 있다.

df.drop(columns='one')
=>
	two
a	1.0
b	2.0
c	3.0
d	4.0

df.drop(index='d')
=>
	one	two
a	1.0	1.0
b	2.0	2.0
c	3.0	3.0

drop() 메서드를 통해 바뀐 값은 inplace=True로 값을 바꾸거나 새로운 변수에 할당하여 바꿀 수 있다.

10. rename()

rename() 메서드는 axis에 따라 열 또는 행의 이름을 다시 짓는다.

df.rename({'one':'One', 'two':'Two'}, axis=1)
=>
	One	Two
a	1.0	1.0
b	2.0	2.0
c	3.0	3.0
d	NaN	4.0

rename() 메서드를 통해 바뀐 값은 inplace=True로 값을 바꾸거나 새로운 변수에 할당하여 바꿀 수 있다.

11. iterrows()

iterrows() 메서드는 행을 순회할 수 있는 메서드이다. for문을 통해 순회 가능하다.

d = {"one": range(20), "two": np.random.randn(20)}
df = pd.DataFrame(d)

for row_index, row in df.iterrows():
  print(row_index, row, sep='\n')
=>
0
one    0.000000
two   -0.125766
Name: 0, dtype: float64
1
one    1.000000
two   -0.152203
Name: 1, dtype: float64
2
one    2.000000
two   -0.240819
Name: 2, dtype: float64
...


12. sort_values()
sort_values()는 numeric 값들을 정렬할 수 있는 메서드이다. Dataframe에서 by 파라미터로 값들을 정렬한 Dataframe을 얻을 수 있다.

df.sort_values(by='two')	# 'two' 컬럼으로 정리한 결과이다. 
=>
	one	two
14	14	-2.781958
10	10	-1.367028
6	6	-0.734207
3	3	-0.728144
9	9	-0.392017
7	7	-0.361294
2	2	-0.240819
1	1	-0.152203
0	0	-0.125766
13	13	-0.053284
15	15	0.059970
4	4	0.161150
12	12	0.329410
18	18	0.497063
8	8	0.603282
16	16	1.048316
19	19	1.195920
5	5	1.272177
17	17	2.027803
11	11	2.113412

 
13. select_dtypes()

select_dtypes() 메서드는 include 또는 exclude 파라미터로 해당 데이터 타입을 가진 열들만 추출해내는 메서드이다.

df = pd.DataFrame(
    {
        "string": list("abc"),
        "int64": list(range(1, 4)),
        "uint8": np.arange(3, 6).astype("u1"),
        "float64": np.arange(4.0, 7.0),
        "bool1": [True, False, True],
        "bool2": [False, True, False],
        "dates": pd.date_range("now", periods=3),
        "category": pd.Series(list("ABC")).astype("category"),
    }
)
df.select_dtypes(include='number')
=>
	int64	uint8	float64
0	1	3	4.0
1	2	4	5.0
2	3	5	6.0