如何拆分年薪与日薪薪资?基于pd.read_csv的CSV文件能否实现指定输出?
Absolutely! Splitting annual and daily salary data from your CSV and outputting in your desired format is totally doable with pandas. Let's break this down based on common scenarios of how your salary data might be structured:
If your salary data combines the numeric amount and its type (annual/daily) in a single column (say, named salary_info), here's how to split and extract the data:
- Load your data (you already have this step covered):
import pandas as pd salary = pd.read_csv('./datasets/salary.csv')
- Split the salary column into amount and type:
We'll use string splitting to separate the two parts, then convert the amount to a numeric type for future calculations:
# Split the salary info into two distinct columns salary[['salary_amount', 'salary_type']] = salary['salary_info'].str.split('/', expand=True) # Convert amount from string to numeric format salary['salary_amount'] = pd.to_numeric(salary['salary_amount'])
- Separate annual and daily salary datasets:
Filter the original DataFrame to create two separate datasets based on the salary type:
annual_salary = salary[salary['salary_type'].str.contains('年')].copy() daily_salary = salary[salary['salary_type'].str.contains('日')].copy()
- Output in your desired format:
You can save these to new CSV files, print them in a readable table, or format them however you need:
# Save to separate CSV files (excluding the index column) annual_salary.to_csv('./datasets/annual_salary.csv', index=False) daily_salary.to_csv('./datasets/daily_salary.csv', index=False) # Or print a subset of columns for quick verification print("Annual Salary Data:\n", annual_salary[['employee_id', 'salary_amount']]) print("\nDaily Salary Data:\n", daily_salary[['employee_id', 'salary_amount']])
If your CSV already has separate columns (e.g., a numeric salary column and a salary_type column with values like "annual" or "daily"), the process is even simpler:
import pandas as pd salary = pd.read_csv('./datasets/salary.csv') # Split into annual and daily datasets directly annual_salary = salary[salary['salary_type'] == 'annual'].copy() daily_salary = salary[salary['salary_type'] == 'daily'].copy() # Output as needed annual_salary.to_csv('./datasets/annual_salary.csv', index=False) daily_salary.to_csv('./datasets/daily_salary.csv', index=False)
If your CSV has a different structure (like unique column names, unusual formatting for salary values, or other edge cases), share a sample of your data or column details, and I can adjust the code to match your exact needs.
内容的提问来源于stack exchange,提问作者Edg

