
pd.Series에서 다중 인덱스를 생성할 때 pd.MultiIndex.from_tuples()를 사용함.기본 코드:
import pandas as pd
import numpy as np
index = pd.MultiIndex.from_tuples([('A', 1), ('A', 2), ('B', 1), ('B', 2)])
s = pd.Series([10, 20, 30, 40], index=index)
print(s)
출력:
A 1 10
2 20
B 1 30
2 40
dtype: int64
print(s['A'])
출력:
1 10
2 20
dtype: int64
loc 속성 사용)print(s.loc['A', 1])
출력:
10
print(s.loc[['A', 'B']])
출력:
A 1 10
2 20
B 1 30
2 40
dtype: int64
df = s.unstack()
print(df)
출력:
1 2
A 10 20
B 30 40
print(df.stack())
출력:
A 1 10
2 20
B 1 30
2 40
dtype: int64
pd.MultiIndex.from_product()를 사용하여 다중 행 및 열 인덱스를 생성할 수 있음.columns = pd.MultiIndex.from_product([['X', 'Y'], ['A', 'B']])
df = pd.DataFrame(np.arange(16).reshape(4, 4), index=index, columns=columns)
print(df)
swaplevel()을 사용하여 인덱스의 레벨을 교환할 수 있음.print(df.swaplevel())
sort_index()를 사용하여 정렬 가능.print(df.sort_index())
groupby(level=0)을 사용하여 특정 레벨 기준으로 그룹화 가능.print(df.groupby(level=0).sum())
set_index() 메소드df = pd.DataFrame({'A': ['foo', 'bar', 'baz'], 'B': [1, 2, 3]})
df.set_index('A', inplace=True)
print(df)
출력:
B
A
foo 1
bar 2
baz 3
reset_index() 메소드df.reset_index(inplace=True)
print(df)
출력:
A B
0 foo 1
1 bar 2
2 baz 3
drop=True 옵션df.reset_index(drop=True, inplace=True)
print(df)
출력:
B
0 1
1 2
2 3
dropna=False 옵션을 사용하면 NaN 값도 유지됨.print(df.stack(dropna=False))
pop() 메소드 사용 시 주의해야 함.df['C'] = [10, 20, 30]
removed_column = df.pop('C')
print(df)
출력:
A B
0 foo 1
1 bar 2
2 baz 3
pivot())df = pd.DataFrame({'A': ['X', 'X', 'Y', 'Y'], 'B': [1, 2, 1, 2], 'C': [10, 20, 30, 40]})
pivot_df = df.pivot(index='A', columns='B', values='C')
print(pivot_df)
출력:
B 1 2
A
X 10 20
Y 30 40
pd.melt() 함수id_vars 키워드 인자를 활용하여 변환.melted_df = pd.melt(df, id_vars=['A'])
print(melted_df)
출력:
A variable value
0 X B 1
1 X B 2
2 Y B 1
3 Y B 2
4 X C 10
5 X C 20
6 Y C 30
7 Y C 40
pivot()과 unstack() 비교set_index()와 unstack()을 연속 적용한 결과와 동일함.print(df.set_index(['A', 'B']).unstack())