Python/Pandas&Numpy

pandas Tricks_01 👉🏻 'Reverse (row/column) Order' (Kevin by DataSchool)

metamong 2022. 3. 23.

Q) 데이터프레임이 주어졌다. 근데 내가 원하는 데이터는 행 기준 아래 부분. 데이터 용량이 워낙 커서 데이터 훑기도 힘들다면

 

A) '행과 열 순서 바꾸기' 👉🏻 .loc[::-1] & .loc[:,::-1] 사용하기

(tail()도 있지만, 데이터프레임 자체의 행/열 구성을 바꿔주지는 않는다!)

 

1> seaborn 내장 iris dataset 가져오자.

 

import seaborn as sns
df_iris = sns.load_dataset('iris')
df_iris.head()

 

 

2> loc[::-1] 사용.

 

df_iris.loc[::-1].head()

 

 

3> 마음에 드는데 index가 걸린다. 다시 index를 reset 해보자(즉, index를 0부터 맞추잔 소리) (reset_index)

→ 원래 reset_index하면 기존의 index를 하나의 column으로 만들어버리는데 (그게 default) 만들지 않게 'drop = True' 설정

 

 

df_iris = df_iris.loc[::-1].reset_index(drop=True)
df_iris.head()

 

 

4> 열(column)도 순서를 바꿀 수 있다! .loc[:,::-1] 사용

 

df_iris = df_iris.loc[:,::-1].head()
df_iris

 

 

<행/열 바꾸기 끄~~읕!> ✌🏻


* 출처1) https://youtu.be/RlIiVeig3hc     

* 출처2) https://pandas.pydata.org/docs/reference/api/pandas.DataFrame.reset_index.html

'Python > Pandas&Numpy' 카테고리의 다른 글

pandas Tricks_02 👉🏻 'Select columns by Data Type' (Kevin by DataSchool)  (0) 2022.03.25
list comprehension  (0) 2022.03.23
pandas functions - cut, qcut  (0) 2022.03.23
Pandas  (0) 2022.03.21
NumPy intro. + fundamentals 1/2  (0) 2022.03.20

댓글