빅데이터 분석기사/데이터마님

데이터 전처리 100문제 Q20~43 - duplicate(), str, isin()

유방울 2024. 5. 5. 02:24

filtering

df.loc[df['quantity']==3].head()

reset_index(drop=True)

# q22 reset_index() 안에 drop True 안 쓰면 index 칼럼이 새로 생김 꼭 추가하기
ans = df.loc[df['quantity']==3].reset_index(drop=True).head()
print(ans)

and -> & !!!

df['new_price'] = df.new_price 

# q27 조건 and -> & 틀림
# ()로 묶기
# 복잡할 때는 df.new_price 가능
# df.loc[(df['new_price'] <= 9) & (df['item_name'] == 'Chicken Salad Bowl')]
df.loc[(df.new_price <= 9) & (df.item_name == 'Chicken Salad Bowl')]

sort_values('new_price', ascending=False)

파라미터 ascending

# sort_values 내림차순 파라미터는 ascendingd임
# 기본은 오름차순, False는 내림차순
ans = df.sort_values('new_price', ascending=False).reset_index(drop=True)
ans

drop_duplicates('item_name', keep='last')

파라미터 keep

# q33 중복행 제거 drop_duplicates('item_name') 파라미터로 안에 기준 칼럼 적기
ans = df.loc[(df.item_name =='Steak Salad')|(df.item_name=='Bowl')]
ans = ans.drop_duplicates('item_name')
ans

 

#  q34 중복 제거시 마지막 케이스만 남기는 파라미터 keep='last'
ans = df.loc[(df.item_name=='Steak Salad') | (df.item_name=='Bowl')]
ans.drop_duplicates('item_name', keep='last')

loc 이용해서 대체하기

# q36 item_name 값이 lzze 데이터를 -> Fizzy Lizzy로 수정
# loc 인덱스로 수정가능 
# str로는 어떻게 하는지 모르겠넝~
df.loc[df.item_name =='Izze', 'item_name'] = 'Fizzy Lizzy'
ans = df
ans

Isin()

#  NaN 값을 대체하는 거니까 뒤에 등호는 = 이 아닌 ==을 이용
df.loc[df.choice_description.isnull(), 'choice_description'] = 'NoData'
ans = df
ans

~ : 부정

# q40 
# contain 가 포함하는 것이고 포함하지 않은 것을 알고 싶다면 조건에 ~ 부정을 붙이면 됨
len(df.loc[~df.choice_description.str.contains('Vegetables')])
# q43
# 리스트 안에 있는 것이 포함된다는 개념이면 isin() 사용함
lst =[1.69, 2.39, 3.39, 4.45, 9.25, 10.98, 11.75, 16.98]
df.loc[df.new_price.isin(lst)].head()

str

str.contains()

# q29 포함하는 내용 contains 사용!! 틀림
ans = df.loc[df['item_name'].str.contains('Chips')]
print(ans)

str.startsiwth()

 

# 시작하는 것 메소드는 start아니고 startswith 임!!
df[df.item_name.str.startswith('N')].head()

str.len()

# q42
# 값의 단어 갯수 str에서 len 함수 쓰면 됨 ㄷㄷ 몰랐음 첨 알았다!!!!
df.loc[df.item_name.str.len() >= 15].head()