我有一个带货币的 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
只需将
)
添加到现有命令中,然后将 (
转换为 -
即可使括号中的数字变为负数。 然后转换为浮点数。
(df['Currency'].replace( '[\$,)]','', regex=True )
.replace( '[(]','-', regex=True ).astype(float))
Currency
0 1
1 2000
2 -3000
这是如果您想确保将其添加到 DataFrame 中。
df['Currency']=(df['Currency'].replace( '[\$,)]','', regex=True ) .replace( '[(]','-', regex=True ).astype(float))
这是一个实用函数,可以接受 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)