Pandas DataFrame Apply () function (1)

Source: Internet
Author: User

Previously written pandas DataFrame Applymap () function

and pandas Array (pandas Series)-(5) Apply method Custom function

The applymap () function of the pandas DataFrame and the apply () method of the pandas Series are processed separately for the entire object's previous values, returning a new object.

The apply () function of Pandas DataFrame, although it also acts on each value of DataFrame, but the accepted parameter is not the individual value itself, but the rows (or columns) in the DataFrame, return a new Row (column):

Like the next set of data: records the results of 10 students in two exams:

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'])

The students are required to convert their grades into a,b,c,d,e, five levels, and the conversion rules are as follows:

20% of the score before the test scores get a

20%-50% of Get B

50%-80% of Get C

80%-90% of Get D

90%-100% of Get E

First, you can use the . Qcut () method to write a function that converts data values by interval: Pandas's Qcut () method

def Convert_grades_curve (exam_grades):     return pd.qcut (Exam_grades, [0, 0.1, 0.2, 0.5, 0.8, 1], labels=['E'D  'C'B'A  '])

And then apply this function to the entire dataframe.

print grades_df.apply (convert_grades_curve)
        exam1 exam2andre       F     fbarry       b     bchris       c     Cdan         c     cemilio      b     BFred        c     Cgreta       A     ahumbert     D     DIvan        a     ajames       b     B

As can be seen, the Dataframe apply () method defaults to the columns of the dataframe.

If you want to work on a row, you can set the parameter axis

dataframe.apply (func,axis=0)

Pandas DataFrame Apply () function (1)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.