Get the App
SLTechnology News&Howtos  ›  Internet Technology  › 

How to use the map () function in python

Shulou Source: shulou.com Published: 2022-06-02 06:08:41 09月25日 Update

Today, I will talk to you about how to use the map () function in python. Many people may not know much about it. In order to make you understand better, the editor has summarized the following for you. I hope you can get something according to this article.

Function introduction

Map () maps the specified sequence based on the function provided. The first argument, function, calls the function function with each element in the argument sequence, returning a new list of values returned by each function function.

Grammar

Map () function syntax: map (function, iterable,...)

Parameters.

Function-- function iterable-- one or more sequences

Return value

Python 2.x returns the list. Python 3.x returns the iterator.

Example

The following example shows the use of map ():

> def square (x): # calculate the square

... Return x * * 2

> map (square, [1pm 2min 3pm 4pm 5]) # calculate the square of each element of the list

[1, 4, 9, 16, 25]

> map (lambda x: X * * 2, [1, 2, 3, 4, 5]) # use lambda anonymous functions

[1, 4, 9, 16, 25]

# provides two lists to add list data in the same location

> map (lambda x, y: X + y, [1,3,5,7,9], [2,4,6,8,10])

[3, 7, 11, 15, 19]

Applied data cleaning

Suppose we get the following CSV data:

Serial number city 1 Shanghai, China 2 Beijing, China 3 Australia 4 United States

Our aim is to extract Chinese countries and cities into two columns, and then foreign countries and cities remain the same. How can it be realized? This uses the map () function that we just put, and acts the city column on the function we defined. Let's see how to implement it.

# cities: extract countries and cities

Def transform_country (x):

If 'China' in x:

Return 'China'

Else:

Return x

Def transform_city (x):

If 'China' in x:

Return x [2:]

Else:

Return x

Df ['country'] = df. City .map (lambda x: transform_country (x))

Df ['city'] = df. City .map (lambda x: transform_city (x))

The final goal turns out to be this:

Serial number: national city 1, Shanghai, China 2, Beijing, China 3 Australia 4 USA

After reading the above, do you have any further understanding of how to use the map () function in python? If you want to know more knowledge or related content, please follow the industry information channel, thank you for your support.

Tags: Function city China country content parameter sequence data Australia Australia United States element instance serial number grammar Shanghai Beijing same two location Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Redmi Apple OPPO Reno vpn MariaDB