Python Library/Pandas 31

[Pandas - Python] Pivot Tables and Cross-Tabulation - pivot_table(), crosstab()

데이터는 다음과 같습니다. tips[:6] total_billtipsmokerdaytimesizetip_pct 016.991.01NoSunDinner20.059447 110.341.66NoSunDinner30.160542 221.013.50NoSunDinner30.166587 323.683.31NoSunDinner20.139780 424.593.61NoSunDinner40.146808 525.294.71NoSunDinner40.186240 이후 pivot_table을 day와 smoker에 대해 설정하고, 함수를 적용하면 tips.pivot_table(index=['day', 'smoker']) sizetiptip_pcttotal_bill daysmoker FriNo2.2500002.8125000.151..

[Pandas - Python] 지금까지의 예시 + 코드에 대한 설명

s = pd.Series(np.random.randn(6)) s[::2] = np.nan s 0 NaN 1 0.050009 2 NaN 3 0.852965 4 NaN 5 -0.023493 dtype: float64 랜덤으로 6개의 숫자를 생성한 후, s에 Series로 할당했고, 2배 간격으로 0, 2, 4의 row에 NaN을 넣었습니다. s.fillna(s.mean()) 0 0.293160 1 0.050009 2 0.293160 3 0.852965 4 0.293160 5 -0.023493 dtype: float64 s의 평균을 fillna를 통해 넣었습니다. 또 다른 예시를 봅시다. states = ['Ohio', 'New York', 'Vermont', 'Florida', 'Oregon', 'Nevad..

[Pandas - Python] Data Aggregation - agg() (데이터 종합)

df key1key2data1data2 0aone-0.2047081.393406 1atwo0.4789430.092908 2bone-0.5194390.281746 3btwo-0.5557300.769023 4aone1.9657811.246435 이때 key1을 기준으로 그룹화 한 뒤, data1에 해당하는 데이터를 연산할 수 있습니다. grouped = df.groupby('key1') grouped['data1'].quantile(0.9) key1 a 1.668413 b -0.523068 Name: data1, dtype: float64 grouped.describe() data1data2 countmeanstdmin25%50%75%maxcountmeanstdmin25%50%75%max key1 a3.00..

[Pandas - Python] GroupBy Mechanics - groupby() (그룹으로 묶기)

우선 데이터를 생성하겠습니다. df = pd.DataFrame({'key1' : ['a', 'a', 'b', 'b', 'a'], 'key2' : ['one', 'two', 'one', 'two', 'one'], 'data1' : np.random.randn(5), 'data2' : np.random.randn(5)}) df key1key2data1data2 0aone-0.2047081.393406 1atwo0.4789430.092908 2bone-0.5194390.281746 3btwo-0.5557300.769023 4aone1.9657811.246435 이때 data1열을 key1을 기준으로 그룹으로 묶겠습니다. grouped = df['data1'].groupby(df['key1']) grouped ..

[Pandas - Python] Reshaping with Hierarchical Indexing - stack(), unstack() (계층적 인덱싱의 구조 변환)

data = pd.DataFrame(np.arange(6).reshape((2, 3)), index=pd.Index(['Ohio', 'Colorado'], name='state'), columns=pd.Index(['one', 'two', 'three'], name='number')) data numberonetwothree state Ohio012 Colorado345 result = data.stack() result state number Ohio one 0 two 1 three 2 Colorado one 3 two 4 three 5 dtype: int32 result.unstack() numberonetwothree state Ohio012 Colorado345 여기까지는 지금까지 공부한 내용으로..

[Pandas - Python] Concatenating Along an Axis - concat() (특정 열, 행을 기준으로 연결하는 법)

데이터 프레임, 혹은 시리즈나 numpy object를 사슬처럼 연결하는 메소드인 concatenate()와 concat()에 대해 알아봅시다. arr = np.arange(12).reshape((3, 4)) arr array([[ 0, 1, 2, 3], [ 4, 5, 6, 7], [ 8, 9, 10, 11]]) np.concatenate([arr, arr], axis=1) array([[ 0, 1, 2, 3, 0, 1, 2, 3], [ 4, 5, 6, 7, 4, 5, 6, 7], [ 8, 9, 10, 11, 8, 9, 10, 11]]) 보시다시피 axis = 1을 줌으로써, 열을 기준으로 합쳤습니다. 이제 Series에 대해서 연결해봅시다. s1 = pd.Series([0, 1], index=['a',..

[Pandas - Python] Merging on Index - merge(), join()

만약 column을 기준으로 합치려고 하는데, 합치려고 하는 컬럼이 인덱스에 있다면 어떻게 해야할까요? 우선 두 개의 데이터 프레임을 만들었습니다. left1 = pd.DataFrame({'key': ['a', 'b', 'a', 'a', 'b', 'c'], 'value': range(6)}) right1 = pd.DataFrame({'group_val': [3.5, 7]}, index=['a', 'b']) left1 keyvalue 0a0 1b1 2a2 3a3 4b4 5c5 right1 group_val a3.5 b7.0 이때 right1의 인덱스에 a,b라는 key가 들어가있습니다. 이를 해결하기 위해서는 right_index = True를 해주면 됩니다. pd.merge(left1, right1, l..

[Pandas - Python] Database-Style Dataframe Joins - merge() (데이터 베이스 병합하기)

두 개의 데이터 프레임을 생성해봅시다. df1 = pd.DataFrame({'key': ['b', 'b', 'a', 'c', 'a', 'a', 'b'], 'data1': range(7)}) df2 = pd.DataFrame({'key': ['a', 'b', 'd'], 'data2': range(3)}) df1 keydata1 0b0 1b1 2a2 3c3 4a4 5a5 6b6 df2 keydata2 0a0 1b1 2d2 이때 두 개의 데이터 프레임을 병합하는 merge() 함수를 사용해봅시다. pd.merge(df1, df2) keydata1data2 0b01 1b11 2b61 3a20 4a40 5a50 어떤 column을 기준으로 병합할지 명시하지 않았지만, 알아서 두 개의 데이터 프레임에 overlap..

[Pandas - Python] Indexing with a DataFrame's Columns - set_index() (데이터 프레임의 열로 인덱싱 하는 법)

frame = pd.DataFrame({'a': range(7), 'b': range(7, 0, -1), 'c': ['one', 'one', 'one', 'two', 'two', 'two', 'two'], 'd': [0, 1, 2, 0, 1, 2, 3]}) frame abcd 007one0 116one1 225one2 334two0 443two1 552two2 661two3 원본 데이터 입니다. 이때 c, d를 인덱스로 설정하고 싶다면, frame.set_index(['c', 'd']) 하면 됩니다. frame2 = frame.set_index(['c', 'd']) frame2 ab cd one007 116 225 two034 143 252 361 보시다시피 c와 d를 기준으로 인덱스가 설정되었습니다. ..