pandas DataFrame applymap()函數

來源:互聯網
上載者:User

標籤:imp   div   成績   .data   core   mil   資料   10個   處理   

pandas DataFrame的 applymap() 函數可以對DataFrame裡的每個值進行處理,然後返回一個新的DataFrame:

import pandas as pddf = 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   c0  2  11   61  3  21  112  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 exam2Andre       F     FBarry       B     DChris       C     FDan         C     FEmilio      B     DFred        C     FGreta       A     CHumbert     D     FIvan        A     CJames       B     D

 

pandas DataFrame applymap()函數

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.