pandas 기본 문법

DataFrame 생성 방법


  • list이용

    1
    2
    3
    4
    5

    import pandas as pd

    frame = pd.DataFrame([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
    frame
출력

0 1 2
0 1 2 3
1 4 5 6
2 7 8 9
  • Dictionary 이용

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    import pandas as pd

    data = {
    'age' : [20,39,41],
    'height' : [176, 182, 180],
    'weight' : [73, 78, 69]
    }
    indexName = ['사람1', '사람2', '사람3']

    frame = pd.DataFrame(data, index = indexName)
    frame
출력

age height weight
사람1 20 176 73
사람2 39 182 78
사람3 41 180 69

Sample Dataset 가져오기


위처럼 직접 DataFrame을 만드는 것이 아닌 제공하는 Dataset을 직접 가져오는 방법도 있다.
Dataset을 가져오는 방법은 다음과 같다.

  1. Dataset Github에 접속하고 가져오고싶은 데이터셋을 고른다.
  2. 예를들어 flights.csv 를 가져오고 싶다면
    1
    2
    3
    4
    import seaborn as sns
    flights = sns.load_dataset("flights") #여기까지가 가져오기
    flights.head(5) # 다섯번째 행의 데이터까지만 출력
    flights["year"] # 'year'열만 출력
    위와 같이 제공되는 데이터셋을 가져올 수 있다.

DataFrame 조회 방법


기본적인 조회 방법

DataFrame의 기본적인 조회 방법은 다음과 같다.


1
2
# 위에서 가져온 데이터셋 flights를 사용
flights.head() # 데이터프레임의 가장 첫부분부터 표시
출력

year month passengers
0 1949 Jan 112
1 1949 Feb 118
2 1949 Mar 132
3 1949 Apr 129
4 1949 May 121

이 때 .head()의 괄호 안에 숫자가 있다면 그 수의 개수만큼 데이터가 출력된다.

  • .tail()


1
flights.tail() #데이터프레임의 가장 뒷부분부터 표시
출력

year month passengers
139 1960 Aug 606
140 1960 Sep 508
141 1960 Oct 461
142 1960 Nov 390
143 1960 Dec 432

.tail()역시 마찬가지로 괄호안에 숫자가 있다면 수의 개수만큼 데이터가 출력된다.

  • .index


데이터프레임의 인덱스를 표시하는 방법도 있다.

1
flights.index
RangeIndex(start=0, stop=144, step=1)

열(Column) 조회 방법

1
2
3
4
5
6
7
8
9
10
#열(Column) 조회
print ("* 열 조회 - 1")
print (frame['age'])
print ("* 열 조회 - 2")
print(frame.age)

#특정 열의 특정 값을 조회하고 싶을때
print("* 특정 열 의 특정 값 조회")
print(frame['age'][1])
print(frame.height[2])
출력
* 열 조회 - 1
사람1    20
사람2    39
사람3    41
Name: age, dtype: int64
* 열 조회 - 2
사람1    20
사람2    39
사람3    41
Name: age, dtype: int64
* 특정 열 의 특정 값 조회
39
180

행(Row) 조회

행 조회는 열 조회와 조금 다르게 lociloc를 사용해서 조회 할 수 있다.
여기서 loc는 사람이 읽을 수 있는 라벨 값으로 특정 값들을 골라오는 방법이고,
iloc는 행이나 칼럼의 순서를 나타내는 정수로 특정 값을 추출하는 방법이다.

1
2
3
4
5
#행(Row) 조회 (loc)
print("* loc 특정 행 조회")
print(frame.loc['사람1'])

# print(frame.loc[0]) - 조건이 정수이므로 조회 불가
출력
* 특정 행 조회
age        20
height    176
weight     73
Name: 사람1, dtype: int64
loc를 Seq로 조회할 경우
1
2
3
4
5
#행(Row) 조회 (iloc)
print("* iloc 특정 행 조회")
print(frame.iloc[0])

# print(frame.iloc['사람1']) - 조건이 정수가 아니므로 조회 불가
출력
* iloc 특정 행 조회
age        20
height    176
weight     73
Name: 사람1, dtype: int64

DataFrame 수정 방법


열(Column) 추가하기

gender 라는 컬럼을 추가합니다.

1
2
frame_add_col = pd .DataFrame(frame,columns= ['age','height','weight','gender'])
frame_add_col
출력

age height weight gender
사람1 20 176 73 NaN
사람2 39 182 78 NaN
사람3 41 180 69 NaN

컬럼이 추가되었고 어떠한 값도 넣어주지 않았으므로 NaN 값이 출력되고있다.
이제 데이터를 입력해준다.

1
2
frame_add_col['gender'] = ['male', 'male', 'female']
frame_add_col
출력

age height weight gender
사람1 20 176 73 male
사람2 39 182 78 male
사람3 41 180 69 female

행(Row) 추가하기

1
2
3
frame_add_index = frame_add_col.copy()
frame_add_index.loc['사람4'] = [31, 158, 48, 'female']
frame_add_index
출력

age height weight gender
사람1 20 176 73 male
사람2 39 182 78 male
사람3 41 180 69 female
사람4 31 158 48 female

행, 열 삭제하기

drop 메소드를 사용하면 행 또는 열을 삭제할 수 있다.
axis 값은 행이면’0’, 열이면 ‘1’로 지정해주면 된다.

1
2
print('remove age column')
frame_add_col.drop("height", axis=1)
출력
remove age column

age weight gender
사람1 20 73 male
사람2 39 78 male
사람3 41 69 female

그러나 이 경우 기존에 있던 frame_add_col에서 삭제되는게 아니라 삭제된 상태의 프레임을 리턴해준 것이다.
그러므로 기존 프레임에 적용하기 위해서 inplace = True 옵션을 추가로 주어야 한다.

1
2
frame_add_index.drop('사람2', axis=0, inplace = True)
frame_add_index
출력

age height weight gender
사람1 20 176 73 male
사람3 41 180 69 female
사람4 31 158 48 female

References