Pandas批量转换多列数据类型:带美元符字符串转浮点型金额
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

