将货币转换为浮动货币(括号表示负数)

问题描述 投票:0回答:3

我有一个带货币的 df:

df = pd.DataFrame({'Currency':['$1.00','$2,000.00','(3,000.00)']})

     Currency
0       $1.00
1   $2,000.00
2  (3,000.00)

我想将“货币”数据类型转换为浮点型,但我在括号字符串(表示负数)方面遇到问题。这是我当前的代码:

df[['Currency']] = df[['Currency']].replace('[\$,]','',regex=True).astype(float)

这会产生错误:

ValueError: could not convert string to float: (3000.00)

我想要的 dtype float 是:

     Currency
0       1.00
1   2000.00
2  -3000.00
python pandas currency
3个回答
47
投票

只需将

)
添加到现有命令中,然后将
(
转换为
-
即可使括号中的数字变为负数。 然后转换为浮点数。

(df['Currency'].replace( '[\$,)]','', regex=True )
               .replace( '[(]','-',   regex=True ).astype(float))

   Currency
0         1
1      2000
2     -3000

1
投票

这是如果您想确保将其添加到 DataFrame 中。

df['Currency']=(df['Currency'].replace( '[\$,)]','', regex=True ) .replace( '[(]','-',   regex=True ).astype(float))


0
投票

这是一个实用函数,可以接受 pandas 数据框并处理任何列中基于货币的数据。


def handle_currency_column(df: pd.DataFrame) -> pd.DataFrame:
    for column in df.columns:
        try:
            df[column] = (
                df[column]
                .replace(r"[\$,)]", "", regex=True)
                .replace("[(]", "-", regex=True)
                .replace(" ", "", regex=True)
                .replace("", "NaN", regex=True)
                .astype(float)
            )
        except Exception as e:
            # do nothing if column is a non numeric string column
            print(
                f"Error while converting column {column} to float. Error: {e}"
            )
            continue
    return df


用途:

...
df = handle_currency_column(df)
© www.soinside.com 2019 - 2024. All rights reserved.