본문 바로가기
ML, DL/Data Analysis

[Pandas] Part 1. DataFrame, Series, Rename, Remove, Sort, Filter

by Wordbe 2019. 10. 12.
728x90

1. Data Analysis

Using a pandas library in python language

2. Pandas

data_table = read_table('파일명')

tsv, csv. 등등 다양한 파일을 불러올 수 있음.

read_table안의 추가 인수를 소개합니다.

추가 인수 내용
sep='|' |기준으로 데이터를 나눈다, seperate
header=None 데이터 양식에 헤더가 없을 때, 맨 첫번째 행이 헤더가 되는 것을 막는다.
name=user_cols 각 열(column)의 이름을 리스트로 구성해 대입시키면, 헤더 이름을 만들 수 있다.
skiprows=None, skipfooter=None 데이터 안에 note같은 것이 들어있을 때, skip할수 있다.
user_cols = ['user_id', 'age', 'gender', 'occupation', 'zip_code']
users = pd.read_table('http://bit.ly/movieusers', sep='|', header=None, names=user_cols)

3. Pandas Series from a Dataframe

read_table(" ", sep=',')은 read_csv와 같습니다!

read_table은 Dataframe입니다.

ufo = pd.read_csv('http://bit.ly/uforeports')
type(ufo)
>> pandas.core.frame.DataFrame

데이터프레임에서 열을 하나 잡으면 Series입니다.

type(ufo['City'])
>> pandas.core.series.Series

column을 얻는 방법 [], .

ufo['City']
ufo.City

ufo['Colors Reported'] # space가 있는 열은 []만 사용가능
ufo['Location'] = ufo.City + ', ' + ufo.State # +로 열을 합침, assign 할때는 []만 가능

Column을 고른 다는 것은, 데이터베이스에서 project를 한다는 것이죠.

select 구분에 해당하신다고 보시면 되겠습니다.

select city from ufo


4. Parentheses()로 끝나는 명령과 그렇지 않은것 차이

이건, 객체개념을 아시는 프로그래머라면 아실 것 같습니다.

()는 멤버 함수(method)를 호출,

.은 멤버 변수(property)를 호출합니다.

movies.describe() # numeric type을 가진 열들을 반환, ()는 기능을 가진 method

movies.shape # ()이 없는 것은 property(attribute)
movies.dtypes

5. Rename columns in DataFrame

3가지 방법! + 1가지 Tip

1) .rename(columns={})

딕셔너리 안에 {이전값: 바꿀값} 일일이 대응시켜주기.

ufo.rename(columns = {'Colors Reported': 'Colors_Reported', 'Shape Reported': 'Shape_Reported'}, inplace=True)

2) .columns =

새로운 리스트에 바꿀 이름을 미리 적은다음에, 할당해주기

ufo_cols = ['city', 'colors_reported', 'shape_reported', 'state', 'time']
ufo.columns = ufo_cols

3) pd.read_csv('', names='', header=0)

불러올 때부터, header는 0으로 해주고(첫번째 행을 비우겠다는 의미), 그 자리를 ufo_cols 리스트로 대체합니다.

ufo = pd.read_csv('http://bit.ly/uforeports', names=ufo_cols, header=0)

4) Tip: 특정한 패턴을 바꾸고 싶을 때

공백이 있는 칼럼명을 '공백'대신 '_'로 치환해봅시다.

ufo.columns = ufo.columns.str.replace(' ', '_')

6. Remove Columns

axis=0(행), 1(열)

여러개를 제거하고 싶을 때는 리스트안에 여러개를 넣어주면 됩니다.

행을 제거하고 싶을 때는 행의 인덱스를 지정해주면 됩니다.

ufo.drop('Colors Reported', axis=1, inplace=True)

ufo.drop(['City', 'State'], axis=1, inplace=True)

ufo.drop([0, 1] , axis=0, inplace=True)

7. Sort a DataFrame or a Series

dataframe은 테이블(표)을 의미하고,

Series는 그 중 하나의 열을 의미합니다.

movies = pd.read_csv('http://bit.ly/imdbratings')

movies.title.sort_values() # Sort the Series
movies['title'].sort_values() # Sort the Series
movies['title'].sort_values(ascending=False) # 내림차순, 기본값은 오름차순

movies.sort_values('title', ascending=False) # Sort the DataFrame

두 가지 컬럼을 동시에 정렬할 때는, 먼저 정렬하고 싶은 값을 리스트 앞에 써주면됩니다.

movies.sort_values(['content_rating', 'duration']) # content_rating이 먼저 정렬되고, 각각에서 duration이 정렬된다.

8. Filter rows of DataFrame by column value

"상영시간이 200이상 되는 영화를 골라줘"

에 대한 답변은 이렇게 하시면 됩니다.

movies[movies.duration >= 200]

movies.duration은 Series입니다.

Series >= 200 이렇게 하면, pandas는 각 원소비교하여 그 불린값을 리스트로 반환합니다.

즉 [false, false, true, false, ...] 이렇게 나올 것입니다.

booleans = []
for length in movies.duration:
    if length >= 200:
        booleans.append(True)
    else:
        booleans.append(False)

원래는 이렇게 코딩해야 겠지요?

pandas가 더욱더 간편한 이유는 이것을 dataframe의 breacket [] 안에 넣으면, True인 행만 모아서 반환하게 됩니다.

그래서 맨 위와 같은 식이 가능한 것입니다.

그렇다면,

"상영시간이 200이상 되는 영화들의 장르만 알려줘" 는 어떻게할가요?

movies[movies.duration >= 200]['genre']
movies[movies.duration >= 200].genre

뽑아낸 행(movies[movies.duration >= 200]) 중에서, 원하는 열(genre)을 다시 오르면 됩니다.

데이터베이스의 select, where이 겹쳐있네요.

select genre

from movies

where movies.duration >= 200

하지만, 이 경우 오류가 나는 경우가 있기 때문에,

.loc()을 추천합니다. 자세한 건 후에 배우겠습니다.

movies.loc[movies.duration >= 200, 'genre']

Data analysis in Python with pandas

을 참조하여 정리하였습니다.

728x90

댓글