Run The Bridge

Pandas 기초(11) 본문

Python/Pandas

Pandas 기초(11)

anfrhrl5555 2020. 9. 8. 17:00
728x90
반응형
DataFrame을 하나 생성한다.
1
2
3
4
5
6
import pandas as pd
date_list = [{'yyyy-mm-dd''2000-06-27'},
         {'yyyy-mm-dd''2002-09-24'},
         {'yyyy-mm-dd''2005-12-20'}]
df = pd.DataFrame(date_list, columns = ['yyyy-mm-dd'])
df
cs



해당 DataFrame에서 year만 추출하고싶을 때

1
2
def extract_year(column):
    return column.split("-")[0]
cs


1
df['year'= df.['yyyy-mm-dd'].apply(extract_year)
cs


Result



현재 age라는 Column을 새로만들고, 현재년도에서 뺀 숫자를 알고싶을 때

1
2
def get_age(year, current_year):
    return current_year - int(year)
cs


1
df['age'= df['year'].apply(get_age, current_year=2018)
cs


Result


또는 여러개의 함수를 리턴해주고싶을 때

1
2
def get_introduce(age, prefix, suffix):
    return prefix + str(age) + suffix
cs


1
df['introduce'= df['age'].apply(get_introduce, prefix="I am ", suffix = " years old")
cs


Result



하나의 Column만 가지고왔는데 여러개의 Column을 조합하고싶을 때

1
2
def get_introduce_2(row):
    return "I was born in " + str(row.year) + " my age is " + str(row.age)
cs


1
df['introduce'= df.apply(get_introduce_2, axis=1)
cs

axis=1은 열을 뜻한다. 


Result



감사합니다. Thank you!

728x90
반응형

'Python > Pandas' 카테고리의 다른 글

Pandas 기초(13)  (0) 2020.09.08
Pandas 기초(12)  (0) 2020.09.08
Pandas 기초(10)  (0) 2020.09.07
Pandas 기초(9)  (0) 2020.09.07
Pandas 기초(8)  (0) 2020.09.07
Comments