Python案例如何用Pandas做数据映射函数

wen python案例 1

本文目录导读:

Python案例如何用Pandas做数据映射函数

  1. 使用 map() 方法进行简单映射
  2. 使用 replace() 方法进行批量替换
  3. 使用 apply() 方法进行函数映射
  4. 使用 cut() 方法进行连续数据分段
  5. 复杂映射示例:多条件映射
  6. 使用 assign() 方法链式映射
  7. 使用字典和条件进行高级映射
  8. 性能优化:使用 np.selectnp.where

我来详细介绍几种使用Pandas进行数据映射的方法:

使用 map() 方法进行简单映射

import pandas as pd
# 创建示例数据
df = pd.DataFrame({
    'name': ['张三', '李四', '王五', '赵六'],
    'gender': ['M', 'F', 'M', 'F'],
    'grade': ['A', 'B', 'C', 'A']
})
# 性别映射字典
gender_map = {'M': '男', 'F': '女'}
df['gender_cn'] = df['gender'].map(gender_map)
print(df)

使用 replace() 方法进行批量替换

# 成绩等级映射
grade_map = {'A': '优秀', 'B': '良好', 'C': '及格', 'D': '不及格'}
df['grade_desc'] = df['grade'].replace(grade_map)
print(df)

使用 apply() 方法进行函数映射

# 使用自定义函数
def score_to_level(score):
    if score >= 90:
        return 'A'
    elif score >= 80:
        return 'B'
    elif score >= 70:
        return 'C'
    elif score >= 60:
        return 'D'
    else:
        return 'E'
# 创建成绩数据
df_scores = pd.DataFrame({
    'student': ['小明', '小红', '小华', '小刚'],
    'score': [95, 82, 73, 58]
})
df_scores['level'] = df_scores['score'].apply(score_to_level)
print(df_scores)

使用 cut() 方法进行连续数据分段

# 成绩分段
bins = [0, 60, 70, 80, 90, 100]
labels = ['不及格', '及格', '中等', '良好', '优秀']
df_scores['grade'] = pd.cut(df_scores['score'], bins=bins, labels=labels)
print(df_scores)

复杂映射示例:多条件映射

# 创建员工数据
df_emp = pd.DataFrame({
    'emp_id': [1, 2, 3, 4, 5],
    'department': ['技术部', '市场部', '技术部', '财务部', '市场部'],
    'level': ['初级', '中级', '高级', '初级', '中级'],
    'salary': [8000, 12000, 20000, 7500, 13000]
})
# 多条件映射函数
def get_bonus_rate(row):
    """根据部门和级别计算奖金系数"""
    if row['department'] == '技术部':
        if row['level'] == '高级':
            return 0.3
        elif row['level'] == '中级':
            return 0.2
        else:
            return 0.1
    elif row['department'] == '市场部':
        if row['level'] == '高级':
            return 0.25
        elif row['level'] == '中级':
            return 0.15
        else:
            return 0.08
    else:
        return 0.1
# 使用apply应用复杂函数
df_emp['bonus_rate'] = df_emp.apply(get_bonus_rate, axis=1)
df_emp['bonus'] = df_emp['salary'] * df_emp['bonus_rate']
print(df_emp)

使用 assign() 方法链式映射

# 链式操作创建多个映射列
df_transformed = df_scores.assign(
    status=df_scores['score'].apply(lambda x: '通过' if x >= 60 else '未通过'),
    rank=pd.cut(df_scores['score'], bins=[0, 60, 80, 100], labels=['C', 'B', 'A']),
    weighted_score=df_scores['score'] * 0.9
)
print(df_transformed)

使用字典和条件进行高级映射

# 复杂映射示例
def classify_student(score, name_len):
    """根据分数和名字长度分类"""
    if score >= 90 and name_len <= 2:
        return '学霸短名'
    elif score >= 90:
        return '学霸'
    elif score >= 70 and name_len <= 2:
        return '中等短名'
    elif score >= 70:
        return '中等'
    else:
        return '需要加油'
df_scores['classification'] = df_scores.apply(
    lambda row: classify_student(row['score'], len(row['student'])), 
    axis=1
)
print(df_scores)

性能优化:使用 np.selectnp.where

import numpy as np
# 使用 np.select 进行条件映射
conditions = [
    df_scores['score'] >= 90,
    df_scores['score'] >= 80,
    df_scores['score'] >= 70,
    df_scores['score'] >= 60,
    df_scores['score'] < 60
]
choices = ['优秀', '良好', '中等', '及格', '不及格']
df_scores['level_fast'] = np.select(conditions, choices, default='未知')
print(df_scores)
# 1. 简单字典映射 - 使用 map()
# 2. 替换值 - 使用 replace()
# 3. 函数映射 - 使用 apply()
# 4. 连续值分段 - 使用 cut()
# 5. 多条件映射 - 使用 apply() + 自定义函数
# 6. 链式操作 - 使用 assign()
# 7. 条件选择 - 使用 np.select() 或 np.where()

选择建议

  • 简单映射:使用 map()
  • 批量替换:使用 replace()
  • 复杂函数:使用 apply()
  • 性能要求高:使用 np.select()np.where()
  • 连续数据分段:使用 pd.cut()

这些方法可以灵活组合,满足各种数据映射需求。

抱歉,评论功能暂时关闭!