-
[pandas] Multi index에서 single index로, Multi column에서 single column으로 코드 한줄로 변경하기python/pandas 2021. 6. 23. 10:54In [5]:
import numpy as np import pandas as pd
인덱스를 생성하기 위한 array를 생성¶
In [3]:arrays = [ np.array(["bar", "bar", "baz", "baz", "foo", "foo", "qux", "qux"]), np.array(["one", "two", "one", "two", "one", "two", "one", "two"])]
arrays를 index로 하는 DataFrame을 생성한다.¶
In [6]:df = pd.DataFrame(np.random.randn(8, 4), index=arrays)
In [7]:df
Out[7]:0 1 2 3 bar one -0.855668 1.135211 2.552778 -1.380448 two -0.215153 0.035393 -1.616310 -1.621122 baz one 1.222231 -0.758877 -0.531460 -1.359423 two -0.888043 -0.144171 -0.053090 -0.954644 foo one 1.840593 0.697115 0.706164 0.010227 two -0.233461 0.743768 0.162378 -0.432223 qux one -0.333253 0.099729 -0.429405 1.991727 two -0.447069 -0.712880 -0.708186 2.122424 멀티 인덱스로 생성 된 DataFrame을 확인 할 수 있다.
하지만 pivot_table을 생성할때나 의도하지 않게 multiindex가 생기기도 하는데
코드 한줄로 쉽게 제거 할 수 있다.In [8]:df.index = df.index.droplevel()
In [9]:df
Out[9]:0 1 2 3 one -0.855668 1.135211 2.552778 -1.380448 two -0.215153 0.035393 -1.616310 -1.621122 one 1.222231 -0.758877 -0.531460 -1.359423 two -0.888043 -0.144171 -0.053090 -0.954644 one 1.840593 0.697115 0.706164 0.010227 two -0.233461 0.743768 0.162378 -0.432223 one -0.333253 0.099729 -0.429405 1.991727 two -0.447069 -0.712880 -0.708186 2.122424 droplevel( ) 함수를 활용하여 multiindex를 제거할 수 있다.
index가 아닌 column에도 동일하게 사용 가능하다.'python > pandas' 카테고리의 다른 글
pandas.fillna() 누락 된 데이터를 채우는 방법 (0) 2021.08.17 [pandas] MultiIndex droplevel로 제거하기 (0) 2021.07.07 pandas read .txt text 파일 읽기 (0) 2021.07.01