Python

[Jupyter Notebook] SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.Try using .loc[row_indexer,col_indexer] = value instead (후략)

xojuholic 2022. 11. 24.
728x90
반응형

앞서   작성했던, [Jupyter Notebook] FutureWarning: Passing a set as an indexer is deprecated and will raise in a future version. Use a list instead. new_df = df[{'name', 'current_price'}] 글에 이어 작업하다 나타난 Warning 메시지이다.

일단 전체 Warning 메시지는 아래와 같다.

SettingWithCopyWarning: 
A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_indexer,col_indexer] = value instead

See the caveats in the documentation: https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#returning-a-view-versus-a-copy
  new_df['gap'] = new_df['target_price'] / new_df['current_price'] - 1

 

작업했던 코드는 아래와 같다.

new_df = df[['name', 'current_price', 'target_price']]
new_df['gap'] = new_df['target_price'] / new_df['current_price'] - 1

new_df

 

상기 코드 관련한 Warning은 첫 번째 행이 원인(원본에서 일부 추출한 데이터를 가공할 시 원본 자체가 영향을 받을 수 있다는 경고)이라고 현재 수강하는 과정의 강사가 알려줘서 아래와 같이 .copy()를 붙여서 코드를 수정했다.

  • 수정 : new_df = df[['name', 'current_price', 'target_price']]
  • 수정 : new_df = df[['name', 'current_price', 'target_price']].copy()

 

728x90
반응형
SMALL

댓글

💲 추천 글