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 to use Lambda to modify values in Pandas data boxes

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

Share

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

This article mainly shows you "how to use Lambda to modify the value of the Pandas data box", the content is easy to understand, well-organized, hope to help you solve your doubts, the following let the editor lead you to study and learn "how to use Lambda to modify the value of the Pandas data box" this article.

Use Lambda to modify the value in the Pandas data box

Suppose we have the following df data box:

Data = [[1Jing 2jue 3], [4Jer 5Jer 6], [7Med 8Jet 9]] df = pd.DataFrame (data, columns= [0Met 1Jet 2]) IN [1]: print (df) OUT [1]: 0 1 20 1 2 3 1 4 5 6 2 7 8 9

Now, for some reason, you need to add the value of 01 to the number in column 0. A common method is to define a function to accomplish this task, and then use the apply function to modify the value of a column.

Def add_numbers (x): return f' {x} 01'df [0] = df [0] .apply (add_numbers) IN [1]: print (df) OUT [1]: 01 20 101 2 3 1 401 5 6 2 701 8 9

This is not complicated, but it is impractical to create a function for each change in the data box. That's when lambda came in handy.

The lambda function is similar to a normal Python function, but it can be defined without a name, which makes it a nice single line of code. The previously used code can be reduced in the following ways.

Df [0] = df [0] .apply (lambda XRU f'{x} 01')

Lambda becomes very useful when you don't know if you can access a series of properties to modify data.

For example, column 0 contains letters, and we want to capitalize them.

# if you know that .str exists, you can do this df [0] = df [0] .str.title () # if you don't know .str, you can still capitalize df [0] = df [0] .apply (lambda x: x.title ()) above is all the content of the article "how to use Lambda to modify the value in the Pandas data box". Thank you for reading! I believe we all have a certain understanding, hope to share the content to help you, if you want to learn more knowledge, welcome to follow the industry information channel!

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