[pandas] TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal' 해결기

2023. 5. 8. 15:51·Python/pandas

문제 발단

rel(상관 O) 컬럼의 값에는 1을, irrel(상관 X) 컬럼의 값에는 -0.2 값을 곱하여 더한 뒤, total_cnt로 나눠 표준화를 하고자 할 때 아래 코드를 사용했다.

df['score'] = df.apply(lambda x: (x['rel']*1 - 0.2*x['irrel'])/x['total_cnt'], axis=1)

이때 발생했던 오류가 바로 TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal' 이다.

해당 오류는 pandas의 DataFrame에 .apply() 메서드를 사용할 때 발생했던 오류로, 파이썬에서 float 타입과 decimal.Decimal 타입 사이의 연산을 지원하지 않기 때문에 발생한다.

이를 해결하기 위해서는 decimal.Decimal 형식의 변수를 float로 변환하여 계산해야 한다.

 

Step 1.

먼저, DataFrame을 살펴보자.

import decimal

df = pd.DataFrame({'rel': [decimal.Decimal('10.5'), decimal.Decimal('7.8')],
                   'irrel': [decimal.Decimal('1.2'), decimal.Decimal('3.4')],
                   'total_cnt': [decimal.Decimal('100'), decimal.Decimal('50')]})
# 결과
    rel    irrel    total_cnt
0  10.5  1.20000       100.0
1   7.8  3.40000        50.0

 

Step 2.

다시, rel(상관 O) 컬럼의 값에는 1을, irrel(상관 X) 컬럼의 값에는 -0.2 값을 곱하여 더한 뒤, total_cnt로 나눠 표준화를 하고자 할 때 각각의 컬럼을 float()으로 감싸준다.

df['score'] = df.apply(lambda x: (float(x['rel'])*1 - 0.2*float(x['irrel']))/float(x['total_cnt']), axis=1)

여기서 'axis=1' 옵션의 의미는 함수를 DataFrame의 각 행(row)에 적용하여 결과를 반환하도록 지정한다는 의미다.

(default 값으로 'axis=0'로 지정되어 있으며, 'axis=0' 옵션은 DataFrame의 각 열(column)에 적용하여 결과를 반환하게 된다.)

 

결과

# 결과
    rel irrel total_cnt  score
0  10.5   1.2     100.0  0.099
1   7.8   3.4      50.0  0.128

정상적으로. apply() 메서드가 수행됐다.

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

[pandas] 두 개의 DataFrame을 SQL처럼 JOIN 하는 방법  (0) 2023.05.08
[python] pandas DataFrame Index 초기화  (0) 2023.02.22
'Python/pandas' 카테고리의 다른 글
  • [pandas] 두 개의 DataFrame을 SQL처럼 JOIN 하는 방법
  • [python] pandas DataFrame Index 초기화
옐리yelly
옐리yelly
전시회에서 도슨트를 따라다니며 작품 해설을 들으면 더 재밌었던 기억들이 있습니다. 글로 더 재밌는 개발이 되도록 노력하고 있습니다.
  • 옐리yelly
    개발 갤러리
    옐리yelly
  • 전체
    오늘
    어제
    • 모든 글 보기 (82)
      • Project (22)
      • Java (4)
      • Spring (6)
      • Kubernetes (6)
      • Docker (2)
      • JPA (2)
      • Querydsl (2)
      • MySQL (8)
      • ElasticSearch (7)
      • DevOps (4)
      • Message Broker (3)
      • Git & GitHub (2)
      • Svelte (1)
      • Python (8)
        • Python Distilled (4)
        • Anaconda (1)
        • Django (0)
        • pandas (3)
      • Algorithm (1)
      • Computer Science (0)
      • 내 생각 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

    devops
    Project
    프로젝트
    svelte
    OOP
    JPA
    Python
    dataframe
    커넥션 풀
    예약 시스템
    Spring
    blue-green 배포
    gitops
    RabbitMQ
    ncloud
    비사이드
    k8s
    querydsl
    pymysql
    nks
    pandas
    MySQL
    Message Broker
    포텐데이
    docker
    리팩토링
    데드락
    argocd
    성능 테스트
    elasticsearch
  • 최근 댓글

  • 최근 글

  • hELLO· Designed By정상우.v4.10.3
옐리yelly
[pandas] TypeError: unsupported operand type(s) for *: 'float' and 'decimal.Decimal' 해결기
상단으로

티스토리툴바