Previous Pandas DataFrame the Apply () function (1) says How to convert DataFrame by using the Apply function to get a new DataFrame.
This article describes another use of the dataframe apply () function to get a new pandas Series:
The function in apply () receives a row (column) of arguments, returns a value by calculating a row (column), and finally returns a series:
Shows the conversion of the columns of the dataframe into a number, which is then returned to a series:
Give me a chestnut:
ImportNumPy as NPImportPandas as Pddf=PD. DataFrame ({'a': [4, 5, 3, 1, 2], 'b': [20, 10, 40, 50, 30], 'C': [25, 20, 5, 15, 10]})
# Apply the Np.mean () function to the entire dataframe, take the average of each column, and return a series containing the average of each column Printdf.apply (Np.mean)#Results:A 3.0b30.0C15.0Dtype:float64
# Apply the Np.max () function to the entire dataframe, taking the maximum value of each column, and returning a series containing the maximum values for each column
Print
# results: a 5 dtype:int64
If you want to return a series that consists of the second largest number in each column:
def get_second_largest (SE): = Se.sort_values (ascending=False) return sorted_se.iloc[1] def Second_largest (DF): return df.apply (get_second_largest) print( Second_largest (DF))
A 4b +c Dtype:int64
Pandas DataFrame Apply () function (2)