본문 바로가기
pandas

조회, 정렬, 조건필터

by 자동매매 2023. 12. 11.

참조 :

한 권으로 끝내는 <판다스 노트>

https://e-koreatech.step.or.kr/

 

 

from IPython.display import Image
import numpy as np
import pandas as pd
import seaborn as sns

 

1. 출력 방식

df = sns.load_dataset("titanic")
df.head()    # 기본 5행 출력
df.tail()
df.tail(3)   # 3행 출력

 

2. 정보 확인

df.info()

 

<class 'pandas.core.frame.DataFrame'>
RangeIndex: 891 entries, 0 to 890
Data columns (total 15 columns):
 #   Column       Non-Null Count  Dtype   
---  ------       --------------  -----   
 0   survived     891 non-null    int64   
 1   pclass       891 non-null    int64   
 2   sex          891 non-null    object  
 3   age          714 non-null    float64 
 4   sibsp        891 non-null    int64   
 5   parch        891 non-null    int64   
 6   fare         891 non-null    float64 
 7   embarked     889 non-null    object  
 8   class        891 non-null    category
 9   who          891 non-null    object  
 10  adult_male   891 non-null    bool    
 11  deck         203 non-null    category
 12  embark_town  889 non-null    object  
 13  alive        891 non-null    object  
 14  alone        891 non-null    bool    
dtypes: bool(2), category(2), float64(2), int64(4), object(5)
memory usage: 80.7+ KB

 

df.ndim  # 차원
df.shape  # (891, 15)
df.index  # RangeIndex(start=0, stop=891, step=1)
df.columns
df.values
df.T       # 행열 전환

 

df.value_counts (
    normalize=False,  # False면 개수, True면 상대 비율 구함
    sort=True,        # True면 개수 기준 정렬, False면 유일한 값 기준 정렬
    ascending=False,  # False면 내림차순 정렬, True면 오름차순 정렬 
    bins=None,        # None이면 유일값 기준 개수, None 아니면 Bins Group별 개수
    dropna=True       # True면 NaN 무시, False면 유일값에 NaN 포함
    )

 

df["who"].value_counts()
man      537
woman    271
child     83
Name: who, dtype: int64

 

df["pclass"].astype("int32").head()   # type 변경

 

3. 정렬

 

1) index 정렬

df.sort_index().head()                # 오름차순 정렬
df.sort_index(ascending=False).head() # 내림차순 정렬

 

2) 값(열) 기준 정렬

df.sort_values(by='pclass',ascending=False).head()
df.sort_values(by=['fare', 'age']).head()
df.sort_values(by=['fare', 'age'], ascending=[False, True]).head()

 

4. Indexing, Slicing, 조건 필터링

 

df.loc[2:5, 'class':'deck'].head()

 

class	who	adult_male	deck
2	Third	woman	False	NaN
3	First	woman	False	C
4	Third	man	True	NaN
5	Third	man	True	NaN

 

# 조건1 정의
cond1 = df["fare"] > 30

# 조건2 정의
cond2 = df["who"] == "woman"

cond = cond1 & cond2

df.loc[cond1 & cond2]
df.loc[cond1 & cond2, "age"]
df.loc[cond, "age"] = -1

 

sample = pd.DataFrame({"name": ["kim", "lee", "park", "choi"], "age": [24, 27, 34, 19]})
sample
name	age
0	kim	24
1	lee	27
2	park	34
3	choi	19

 

sample["name"].isin(["kim", "lee"])
0     True
1     True
2    False
3    False
Name: name, dtype: bool

'pandas' 카테고리의 다른 글

데이터 전처리, 추가, 삭제, 변환  (0) 2023.12.12
복사와 결측치  (0) 2023.12.12
통계  (0) 2023.12.11
Excel 파일 다루기  (0) 2023.12.11
pandas 기본  (0) 2023.11.30

댓글