pandas & duckdb

조회, 정렬, 필터

wefree 2022. 8. 20. 23:33
import seaborn as sns

df = sns.load_dataset("titanic")

############################################################
# 데이터 살펴보기
df[['pclass', 'age']]   # 특정 column 만 보기
df.head()
df.head(10)

df.tail()
df.tail(10)

df.info()
df.describe()
df.describe(include='object')  # 문자열에 대한 통계
df['who'].value_counts()

############################################################
# 속성
df.ndim
df.shape
df.index
df.columns
df.values
df.T

############################################################
# 타입(dtype) 변경
df['pclass'] = df['pclass'].astype('int32')
df['pclass'].astype('category')


############################################################
# 정렬
df.sort_index(ascending=False)
df.sort_values(by='age', ascending=False, inplace=False)
df.sort_values(by=['pclass', 'age'], ascending=[True, False])


############################################################
# indexing, slicing, 조건필터링
df.loc[3, 'class']  # 5행의 class column 값

df.loc[2:4]  # 2, 3, 4 행 (4도 포함 !!!)
df.loc[:4]
df.loc[2:4, ['age', 'fare', 'who']]
df.loc[2:4, 'class':'deck']


# 필터링 방법 1
cond = (df['who'] == 'man')
df[cond]

# 필터링 방법 2
cond = (df['who'] == 'man')
df.loc[cond]

# 그러나 값을 변경할 경우에는 `필터링 방법 2` 만 동작한다.
cond = (df['who'] == 'man')
# df[cond]['who'] = 'M'  # Error
df.loc[cond, 'who'] = 'M'

df = sns.load_dataset("titanic")
cond1 = df['fare'] > 30
cond2 = df['who'] == 'woman'
df[cond1 & cond2]
df[cond1 | cond2]

# df['fare'] 값이 10.0 보다 작으면 그대로 두고, 크거나 같을 경우 0.0 으로 변경
df['fare'].where(df['fare'] < 10.0, 0.0)

# df['fare'] 값이 10.0 보다 작으면 'fare' 필드 뿐만 아니라 해당 레코드의 모든 필드값을 NaN 으로 채움
df.where(df['fare'] < 10.0)

# isin() 사용하기
sample = pd.DataFrame(
    {'name': ['kim', 'lee', 'park', 'choi'],
     'age': [24, 27, 19, 32]}
)
cond = sample['name'].isin(['kim', 'lee'])
sample[cond]

참고: https://www.udemy.com/course/pandas-i/