You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Pandas批量转换多列数据类型:带美元符字符串转浮点型金额

Solution to Convert Currency Strings to Float in CSV Columns

Got it, let's walk through how to read your CSV into a variable props and convert those dollar-denominated columns to float values smoothly. Since you confirmed there are no NaNs in those columns, we don't have to handle missing value edge cases—nice!

Step 1: Import pandas and read the CSV

First, we'll use pandas (the standard library for tabular data in Python) to load your CSV file into the props variable:

import pandas as pd

# Replace 'your_data.csv' with your actual file path
props = pd.read_csv('your_data.csv')

Step 2: Convert currency strings to float values

We need to clean up the dollar signs ($) and commas (,) from the string values, then convert them to floats. There are two clean ways to do this:

Option 1: Using a custom function (readable for beginners)

Define a helper function to handle the string cleanup, then apply it to the target columns:

def clean_currency(value):
    # Remove $ and commas, then convert to float
    return float(value.replace('$', '').replace(',', ''))

# List of columns to process
target_columns = ['Land Value', 'Improvement Value', 'Total Value']

# Apply the function to each column
props[target_columns] = props[target_columns].applymap(clean_currency)

Option 2: Using lambda (concise one-liner)

If you prefer a more compact approach, use a lambda function with string methods:

target_columns = ['Land Value', 'Improvement Value', 'Total Value']

props[target_columns] = props[target_columns].apply(
    lambda col: col.str.replace('$', '').str.replace(',', '').astype(float)
)

Verify the result

To make sure the conversion worked, you can check the data types of the columns:

print(props[target_columns].dtypes)

You should see float64 for each of the target columns.

内容的提问来源于stack exchange,提问作者Garrus HD

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:13:06