2024.01.04 TIL

녹차·2024년 1월 24일

TIL_Python

목록 보기
5/9

2024.01.04 TIL

01-DataFrame심화-데이터셋 확인하기

customers= pd.read_csv('marketing_campaign.csv', sep='\t')
customers.head()
  • marketing_campaign.csv 을 customers라는 이름의 데이터프레임으로 생성
customers.info()
  • 각 컬럼별 결측값과 타입 확인하기
# 집계통계 기술
customers.describe().round(1)
  • 숫자형 데이터 값 집계하기
# 집계통계 기술 - 숫자 아닌 정보 확인
# 집계통계 기술
customers.describe(exclude=['int','float']).round(1)
  • 숫자 아닌 정보 확인

02 DataFrame과 Series 각 데이터 함수적용(apply)

# 나이 계산 - 데이터셋이 2021.08.23임
2021 - customers['Year_Birth']
  • 나이계산하기 위해 현재년에서 customers['Year_Birth'] 빼기
ID
5524     64
2174     67
4141     56
6182     37
5324     40
         ..
10870    54
4001     75
7270     40
8235     65
9405     67
Name: Year_Birth, Length: 2240, dtype: int64
# 연도 옆에 추가
customers.insert(1, 'Age', 2021 - customers['Year_Birth'])
customers.head()
  • 완성된 나이 데이터를 연도 옆에 추가

  • **.apply(func)**
    • 시리즈에 각 함수 실행결과를 적용시킨다
def classify_age(age):
    if age >= 0 and age <= 12:
        return 'Child'
    elif age >= 13 and age <= 19:
        return 'Teenager'
    elif age >= 20 and age <= 39:
        return 'Young_Adult'
    elif age >= 40 and age <= 64:
        return 'Middle_aged'
    elif age >= 65:
        return 'Elderly'
    else:
        return 'Inavlid_age'
  • 나이를 구분하는 함수 생성
classify_age(9), classify_age(17), classify_age(20), classify_age(59), classify_age(65)

('Child', 'Teenager', 'Young_Adult', 'Middle_aged', 'Elderly')

customers['Age'].apply(classify_age)
ID
5524     Middle_aged
2174         Elderly
4141     Middle_aged
6182     Young_Adult
5324     Middle_aged
            ...
10870    Middle_aged
4001         Elderly
7270     Middle_aged
8235         Elderly
9405         Elderly
Name: Age, Length: 2240, dtype: object

03 Series값매핑과 DataFrame 요소함수적용

  • **Series.map(arg)**
people_set = {
    'Name' : ['Spencer', 'Mark', 'Tom', 'Peter'],
    'Major': ['Computer', 'Science', 'English', 'Computer'],
    'YearOfJoining' : [2020, 2019, 2018, 2017],
    'DriverLicense' : [True, False, False, True],
    'TeacherCertification' : [True, False, False, False],
}
NameMajorYearOfJoiningDriverLicense
0SpencerComputer2020True
1MarkScience2019False
2TomEnglish2018False
3PeterComputer2017True
# map() 으로 매핑 확인해서 값 변환
people['DriverLicense'].map({True :'Yes', False: 'No'})
  • map() 으로 매핑 확인해서 값 변환
0    Yes
1     No
2     No
3    Yes
Name: DriverLicense, dtype: object

  • **Dataframe.applymap(func)**
    • 모든 요소에 apply()를 할 수 있다.
people.applymap(type)

people.applymap(str).applymap(type)
# str같은 경우 Series는 applymap할 필요 없이 가능하나
people['Name'].str.len()

# Dataframe은 .str이 안된다.
people.str()
  • 모든 요소를 str로 변환하고 대문자로 변환하면
# 대문자 만드는 함수
def uppercase(data):
    return data.upper()

people.applymap(str).applymap(uppercase)

04 DataFrame심화-타입 변환(astype)

05-DataFrame심화-값 교체(replace).ipynb

profile
가장 예쁜 꽃은 우여곡절 끝에 피는 꽃

0개의 댓글