Dataframe : 행과 열 조회
- DataFrame.loc[[행이름1, 행이름2, ... ]]
- DataFrame.iloc[[행인덱스1, 행인덱스2 ... ]]
df = pd.DataFrame( np.arange(1,26).reshape(5,5),
index=[ 'row'+str(i) for i in range(1,6)],
columns=[ 'col'+str(i) for i in range(1,6) ])
print(type(df), df.shape, df.size)
df
- 출력
<class 'pandas.core.frame.DataFrame'> (5, 5) 25
|
col1 |
col2 |
col3 |
col4 |
col5 |
row1 |
1 |
2 |
3 |
4 |
5 |
row2 |
6 |
7 |
8 |
9 |
10 |
row3 |
11 |
12 |
13 |
14 |
15 |
row4 |
16 |
17 |
18 |
19 |
20 |
row5 |
21 |
22 |
23 |
24 |
25 |
원하는 행 출력
print(df.loc[['row1', 'row3', 'row5']]) #iloc로 출력 방법 df.iloc[[0, 2, 4]]
- 출력
|
col1 |
col2 |
col3 |
col4 |
col5 |
row1 |
1 |
2 |
3 |
4 |
5 |
row3 |
11 |
12 |
13 |
14 |
15 |
row5 |
21 |
22 |
23 |
24 |
25 |
원하는 행 범위 출력
print(df.iloc[2:5]) # loc로 출력 방법 df.loc['row2':'row4']
- 출력
|
col1 |
col2 |
col3 |
col4 |
col5 |
row2 |
6 |
7 |
8 |
9 |
10 |
row3 |
11 |
12 |
13 |
14 |
15 |
row4 |
16 |
17 |
18 |
19 |
20 |
원하는 열 출력
df.loc[:, ['col1','col3','col5']] #iloc로 출력 방법 df.iloc[:, [0,2,4]]
- 출력
|
col1 |
col3 |
col5 |
row1 |
1 |
3 |
5 |
row2 |
6 |
8 |
10 |
row3 |
11 |
13 |
15 |
row4 |
16 |
18 |
20 |
row5 |
21 |
23 |
25 |
원하는 열 범위출력
df.iloc[:, 1:4] # loc로 출력 방법 df.loc[:, 'col2':'col4']
- 출력
|
col2 |
col3 |
col4 |
row1 |
2 |
3 |
4 |
row2 |
7 |
8 |
9 |
row3 |
12 |
13 |
14 |
row4 |
17 |
18 |
19 |
row5 |
22 |
23 |
24 |
DataFrame 행,열 추가, 삭제
- loc를 통해 없는 행 이름으로 추가할 수 있다.
- iloc를 통해서는 추가할 수 없다.
df.loc['row6'] = [26,27,28,29,30]
df
|
col1 |
col2 |
col3 |
col4 |
col5 |
row1 |
1 |
2 |
3 |
4 |
5 |
row2 |
6 |
7 |
8 |
9 |
10 |
row3 |
11 |
12 |
13 |
14 |
15 |
row4 |
16 |
17 |
18 |
19 |
20 |
row5 |
21 |
22 |
23 |
24 |
25 |
row6 |
26 |
27 |
28 |
29 |
30 |
df = df.drop('row6')
df
|
col1 |
col2 |
col3 |
col4 |
col5 |
row1 |
1 |
2 |
3 |
4 |
5 |
row2 |
6 |
7 |
8 |
9 |
10 |
row3 |
11 |
12 |
13 |
14 |
15 |
row4 |
16 |
17 |
18 |
19 |
20 |
row5 |
21 |
22 |
23 |
24 |
25 |
df['col6'] = [26,27,28,29,30]
df
|
col1 |
col2 |
col3 |
col4 |
col5 |
col6 |
row1 |
1 |
2 |
3 |
4 |
5 |
26 |
row2 |
6 |
7 |
8 |
9 |
10 |
27 |
row3 |
11 |
12 |
13 |
14 |
15 |
28 |
row4 |
16 |
17 |
18 |
19 |
20 |
29 |
row5 |
21 |
22 |
23 |
24 |
25 |
30 |
df.drop(columns=['col6'],inplace=True) #inplace True로 줄시 바로적용
df
|
col1 |
col2 |
col3 |
col4 |
col5 |
row1 |
1 |
2 |
3 |
4 |
5 |
row2 |
6 |
7 |
8 |
9 |
10 |
row3 |
11 |
12 |
13 |
14 |
15 |
row4 |
16 |
17 |
18 |
19 |
20 |
row5 |
21 |
22 |
23 |
24 |
25 |
del df['col5']
df
|
col1 |
col2 |
col3 |
col4 |
row1 |
1 |
2 |
3 |
4 |
row2 |
6 |
7 |
8 |
9 |
row3 |
11 |
12 |
13 |
14 |
row4 |
16 |
17 |
18 |
19 |
row5 |
21 |
22 |
23 |
24 |