isupper, apply

이재은·2024년 6월 18일

EDA Level Test 02

데이터 준비

1. open

with open('./datas/ingredients_list.pkl', 'wb') as f:
    pickle.dump(ingredients_list, f)

1단계

문제 1-1) 성분사전 DataFrame 만들기

2. pd.concat

  • 리스트에 있는 여러 DataFrame을 하나의 DataFrame으로 합침
ingredients_df = pd.concat(ingredients_list_pkl, ignore_index=False)

# ignore_index=False: 합치는 과정에서 원래의 index를 유지할 것인지를 결정
False : 원래 DataFrame들의 index가 그대로 유지
True : index는 리셋되어 0부터 다시 시작됩니다.

문제 1-2) 성분사전 DataFrame 내의 Data 수정하기

3.isupper, islower

  • isupper islower upper lower
a = "I Love Python"
print a.upper() 
> I LOVE PYTHON

a = "I Love Python"
print (a.upper()).isupper() 
> True 

4. apply

#헷갈림 주의 0 : 컬럼적용 1이 index 적용
axis{0 or ‘index’, 1 or ‘columns’}, default 0
Axis along which the function is applied:

0 or ‘index’: apply function to each column.
1 or ‘columns’: apply function to each row.

4. enmerate vs itterroews

문제 1-3) 성분사전 DataFrame 내의 Data 수정하기

4. dic로 dataframe 내용 수정하기

if type(ingredients_str) is str:
        
        # Replace
        for key, value in replace_dict.items():
            ingredients_str = ingredients_str.replace(key, value)

    return ingredients_str

ingredients_df['표준 영문명'] = ingredients_df['표준 영문명'].apply(replace_ingredients_dict)

2단계: Target Data 수정하기

🔔문제 2-1) Target DataFrame 중 Ingredients Column 내의 Data 수정하기

str.find

  • 문자열 내 지정 문자(열)들이 위치한 index반환
    https://blockdmask.tistory.com/569
  • string.find(찾을 문자)
  • string.find(찾을 문자, 시작 Index)
  • string.find(찾을 문자, 시작 Index, 끝 Index)
 # 마지막 마침표 제거
    ingredients_str = ingredients_str[:-1] if ingredients_str[-1] == '.' else ingredients_str

 # delete
    del_list = ['. May Contain']
    for del_str in del_list:
        if del_str in ingredients_str:
            ingredients_str = ingredients_str[:ingredients_str.find(del_str)]
			#찾은 index 전까지 불러옴
cf) 내가 한거 
df_target["Ingredients"] = df_target["Ingredients"].str.rstrip(".")
for i in range(0, 5) :
    df_target.loc[i, "Ingredients"] = df_target["Ingredients"].str.split(". May Contain")[i][0]
# 난도★ 다른건 다 시리즈에서 적용가능한데 왜 str.contains, str.replace안되는거지? 
for old, new in replace_str_dict.items():
    for idx, ingredient in enumerate(df_target['Ingredients']):
        df_target.loc[idx, 'Ingredients'] = ingredient.replace(old, new)    

🔔문제 2-2) Target DataFrame 중 'Ingredients' Column Data 변환하기

3.map
https://www.geeksforgeeks.org/python-map-function/

lambda

조건1: 'Ingredients' Column의 각 데이터를 ', '(쉼표+띄어쓰기)로 분리하여 List로 변환
조건2: 조건1에서 변경한 list의 각 Element 앞뒤의 공백이 있다면 공백을 삭제하세요 
조건3: 'Ingredients List' Column을 새로 생성하여 조건1과 조건2에서 만든 list를 각 행에 맞게 입력

방법 1 
# 조건 1 
df_target["Ingredients List"] =  df_target["Ingredients"].str.split(", ")
#조건2
df_target['Ingredients List'] =  df_target['Ingredients List'].apply(lambda ingrelist: [ingredient.strip() for ingredient in ingrelist])

방법2 (어떤 리스트를 넣으면 , 기준으로 나눔 - 공백삭제 = 다시 리스트해서 반환)
# each_ingredients_str.split(', ')
# 적용함수 : lambda x : x.strip() 리스트에서 벗겨내기 
# 그걸 다시 리스트화
df_target['Ingredients List'] = df_target['Ingredients'].apply(lambda each_ingredients_str: list(map(lambda x: x.strip(), each_ingredients_str.split(', '))))

3단계: 성분사전(Ingredients Dictionary)을 이용하여 Mapping하기

문제 3-1) Target DataFrame 의 'Ingredients List' Column를 Mapping하여 'Code List' Column 만들기

def ingredient_to_code(ingredient_list: list) -> list:

    code_list = []
    for ingredient in ingredient_list:
        try:
            code = ingredients_df[ingredients_df['표준 영문명'].str.lower() == ingredient.lower()]['성분코드'].values[0]
        except:
            code = ingredients_df[ingredients_df['구영문명'].str.lower() == ingredient.lower()]['성분코드'].values[0]
        finally:
            code_list.append(code)
    return code_list
    
df_target['Code List'] = df_target['Ingredients List'].apply(ingredient_to_code)

문제 3-2) 다음 조건을 만족하는 code들을 찾아 그 code들에 해당하는 DataFrame을 구하세요(15점)

profile
Dare to be an optimist

0개의 댓글