pandas DataFrame applymap()函数

pandas DataFrame的 applymap() 函数可以对DataFrame里的每个值进行处理,然后返回一个新的DataFrame:

import pandas as pd

df = pd.DataFrame({
    'a': [1, 2, 3],
    'b': [10, 20, 30],
    'c': [5, 10, 15]
})
    
def add_one(x):
     return x + 1
        
print df.applymap(add_one)
   a   b   c
0  2  11   6
1  3  21  11
2  4  31  16

一个栗子:

这里有一组数据是10个学生的两次考试成绩,要求把成绩转换成ABCD等级:

转换规则是:

90-100 -> A
80-89 -> B
70-79 -> C
60-69 -> D
0-59 -> F

grades_df = pd.DataFrame(
    data={'exam1': [43, 81, 78, 75, 89, 70, 91, 65, 98, 87],
          'exam2': [24, 63, 56, 56, 67, 51, 79, 46, 72, 60]},
    index=['Andre', 'Barry', 'Chris', 'Dan', 'Emilio', 
           'Fred', 'Greta', 'Humbert', 'Ivan', 'James']
)
def convert_to_letter(score):
    if (score >= 90):
        return 'A'
    elif (score >= 80):
        return 'B'
    elif (score >= 70):
        return 'C'
    elif (score >= 60):
        return 'D'
    else:
        return 'F'
      
def convert_grades(grades):
    return grades.applymap(convert_to_letter)

print convert_grades(grades_df)
        exam1 exam2
Andre       F     F
Barry       B     D
Chris       C     F
Dan         C     F
Emilio      B     D
Fred        C     F
Greta       A     C
Humbert     D     F
Ivan        A     C
James       B     D

 

posted @ 2018-07-29 14:17  诗&远方  阅读(7808)  评论(0编辑  收藏  举报