Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

How python uses apply or not apply

2025-01-17 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article will explain in detail how python uses apply or not apply. The editor thinks it is very practical, so I share it with you for reference. I hope you can get something after reading this article.

Apply or not apply

The apply function is sometimes useful if we want to create a new column and take other columns as input.

Def rule (x, y): if x = = 'high' and y > 10: return 1 else: return 0 df = pd.DataFrame ({' C1: ['high',' high', 'low',' low'],'c2: [0,23,17,4]}) df ['new'] = df.apply (lambda x: rule (x [' c1'], x [[c2']), axis = 1) df.head ()

In the above code, we define a function with two input variables and apply it to columns'C1 'and' c2 'using the apply function.

But the problem with the apply function is that it is sometimes too slow. If you want to calculate the maximum values of two columns "C1" and "c2", you can:

Df ['maximum'] = df.apply (lambda x: max (x [' c1'], x ['c2']), axis = 1)

But you will find that it is much slower than this command:

Df ['maximum'] = df [[' C1']] .max (axis = 1)

Note: if you can use other built-in functions to do the same thing (which are usually faster), do not use apply. For example, if you want to round column'c' to an integer, execute round (df ['c'], 0) instead of using the apply function:

Df.apply (lambda x: round (x ['c'], 0), axis = 1)

This is the end of the article on "how python uses apply or not apply". I hope the above content can be of some help to you, so that you can learn more knowledge. if you think the article is good, please share it for more people to see.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report