티스토리 뷰

group by

  • 'col1'을 기준으로 그룹 만들고 'col2'의 평균 값 사용 (mean, sum, count 사용 가능)
d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data=d)

df.groupby('col1')[['col2']].mean()
df.groupby('col1', as_index=False)[['col2']].mean()  # index reset
  • reset index 할 때 already exists 오류날 경우
df.groupby(['col1', 'col2'])[['col2']].count().reset_index(drop=True)

index to columns and reset index

df.reset_index(level=0, inplace=True)
# 위와 같은 기능
df['index'] = df.index  # index 를 'index' 컬럼에
df.reset_index()  # index 초기화
df = df[['index', 'col1', 'col2']]  # 컬럼 순서 변경

sort by

df.sort_values(by=['col1'], axis=0, ascending=True, inplace=True, na_position='first')

series to df

d = {'a': 1, 'b': 2, 'c': 3}
ser = pd.Series(data=d, index=['a', 'b', 'c'])

df = pd.DataFrame(ser, columns=['col1'])
df = ser.to_frame(name='col1')

array to df

ar = np.array([[1,4], [2,5], [3,6]])
df = pd.DataFrame(ar, columns=['col1', 'col2'])

rename columns

df.rename(columns={'col1':'new_col1'}, inplace=True)  # 한 컬럼명 변경
df.rename(columns=lambda x:'new_' + x, inplace=True)  # 전체 컬럼명 변경

concat columns

d = {'col1': [1, 2, 3], 'col2': [4, 5, 6]}
df = pd.DataFrame(data=d)
d2 = {'col1': [1, 2, 3], 'col2': ['a', 'b', 'c']}
df2 = pd.DataFrame(data=d2)

new_df = pd.concat([df, df2], axis=0)  # 행 추가(위아래로 concat)
new_df = pd.concat([df, df2], axis=1)  # 열 추가 (옆으로 concat)

merge

new_df = pd.merge(df, df2[['col1', 'col2']], on='col1')
new_df = pd.merge(pd.merge(df, df2[['col1', 'col2']], on='col1'), df3, on='col1')

DataFrame 과 Series 합치기

data type 변환

df.dtypes
df[['col1']] = df[['col1']].astype('str')

특정 데이터 타입만 선택/제외

df.select_dtypes(include=['object'])  #exclude

 

List comprehension

norm_col = ['a', 'b', 'c']
new_norm_col = [i+'_NORM' for i in norm_col]
# ['a_NORM', 'b_NORM', 'c_NORM']

Dict comprehension

var_color = {'a':'red', 'b':'yellow', 'c':'green'}
new_var_color = {k+'_NORM':v for k, v in var_color.items()}
# {'a_NORM': 'red', 'b_NORM': 'yellow', 'c_NORM': 'green'}

pickle

pd.to_pickle <-> pd.read_pickle

globals()

eval()

댓글
Total
Today
Yesterday
공지사항
최근에 올라온 글
글 보관함