Pandas DataFrame Apply () function (2)

Source: Internet
Author: User

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)

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.