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)