簡體   English   中英

TypeError: 應用 function pandas 系列時不支持從系列轉換為小數

[英]TypeError: conversion from Series to Decimal is not supported when applying function pandas Series

我有以下 function 將值轉換為Decimal object:

def convert_to_decimal(value: str | int, decimals: int) -> Decimal:
    divisor = 10 ** decimals
    return Decimal(value) / divisor

我想將它應用於DataFrame列中的值。 df['numbers']只是一個Series object ,其中包含intNaN值。

我目前的代碼是:

df['numbers'] = df['numbers'].apply(convert_to_decimal(value=df['numbers'],
                                                       decimals=18))

但我收到以下錯誤: TypeError: conversion from Series to Decimal is not supported

我只是想將我的df['numbers']中的每個數字格式化為十進制 object。

您需要 2 處更改:

  1. df[['numbers']]上調用apply() ,它返回 pandas.DataFrame 而不是 pandas.Series。
  2. 將直接調用 function convert_to_decimal轉換為來自 lambda function 的調用。
df[['numbers']].apply(lambda row: convert_to_decimal(value=row['numbers'], decimals=18), axis=1)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM