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

What are the small details of using Python

2025-04-03 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

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

This article introduces the knowledge about "what are the small details of using Python". In the actual case operation process, many people will encounter such difficulties. Next, let Xiaobian lead you to learn how to deal with these situations! I hope you can read carefully and learn something!

01. List generator with only one line of code

Wouldn't it be annoying to write a loop every time you wanted to generate a list? Fortunately Python already has a built-in method that can be solved in one line of code. If you're not familiar with this grammar, it may be a little difficult to understand, but once you get used to the technique, you'll love it!

GIF: How to change a loop into a list generator (Source: Trey Hunner )

The above animation is a good example, the original code is to use the for loop to generate the list method, and the figure step by step to transform it into a list generator with only one line of code, no loop anymore. Isn't that neat?

Here is another example of comparison:

Use cycle:

The output is [1, 4, 9, 16]

Use the generative formula:

The output is also [1, 4, 9, 16]

02 Lambda expression

Obviously this function can not be used a few times, each time to write a large series of function construction code, is not very tired? Don't be afraid, Lambda expressions will save you! Lambda expressions make it easy to create simple, one-time-use, anonymous function objects. Basically, they let you not bother to construct a function, but use it directly.

The basic syntax for Lambda expressions is:

European shaving Chinese, produced by Youda Xuecheng

Remember that Lambda expressions create functions that are no different than ordinary def functions, except that the body of the function is a single expression. Consider the following example:

The output is 10.

Map and Filter functions

Once you master Lambda expressions, using them with map or filter functions can be incredibly powerful.

Specifically, the map() function takes a list and a function that calls a function on each element of the list and puts the result into a new list. In the example below, the map() function iterates over each element in seq, multiplies it by 2, and puts the result into a new list, *** returning the list. The list() function converts the objects returned by map() to list format.

The output is [2, 4, 6, 8, 10]

The filter() function is slightly different, it takes a list and a rule function, and after calling the rule function on each element of the list, it removes all elements that return false from the list and returns the filtered sublist.

The output is [3, 4, 5]

04, the Range and Linspace functions

To generate numpy arrays quickly and easily, you must be familiar with the arange() and linspace() functions. These two functions have their own specific uses, but for us, they both work well to generate numpy arrays (instead of range() ), which is quite useful for data science analysis.

The arange() function returns an arithmetic sequence at the specified step size. In addition to the start and end values, you can customize the step size and data type. Note that the end-value parameter given is not included in the result.

The output is an array object: array([3, 5])

The linspace() function is used similarly, with a slight difference. linspace() returns a sequence of points that divide a given interval into several equal parts. So the parameters you pass in include the start value, the end value, and how many equal parts. Linspace() divides the interval into equal parts, placing the start value, end value, and each of the equal parts into a NumPy array. This is useful for visualizing data and drawing axes.

The output is an array object: array([ 2.0, 2.25, 2.5, 2.75, 3.0])

05. Meaning of coordinate axis (axis parameter) in Pandas

You may have encountered problems with this axis parameter when you want to filter out a column in Pandas or sum data in NumPy matrices. If you haven't seen it yet, it doesn't hurt to know in advance. For example, for a Pandas table:

Before I really understood it, I basically had to re-query which axis value corresponds to which every time I used drop, so many that I lost count. As in the example above, you can probably see that axis is set to 1 if you want to process columns and 0 if you want to process rows, right? But why is that? One of my favorite explanations (or how I remember this) goes like this:

Get the shape attribute of Pandas data table object, you will get a tuple, *** elements of the tuple are the number of rows in the data table, and the second element is the number of columns in the data table. Think about the subscripts of these two elements in Python, the first one is 0, the second one is 1, right? So for the axis parameter, 0 is the number of rows in front, 1 is the number of columns behind, how about it?

Combine data tables with Concat, Merge and Join

If you are familiar with SQL, these concepts should be a piece of cake for you. In any case, these functions are essentially just different ways of merging multiple data tables. Of course, it's not easy to remember which function to use in which case, so let's review it together.

concat() can simply stack one or more data tables in row (or column) direction (depending on whether you pass the axis parameter 0 or 1).

Merge() will align two or more tables with a user-specified column with the same name as the primary key.

Join() is similar to merge() except that join() aligns with the index of the data table rather than with a single column. When a table is missing an index, the corresponding value is null (NaN).

If necessary, you can also consult the official Pandas documentation for more detailed grammar rules and application examples, familiar with some special situations you may encounter.

07. Apply function

You can think of apply() as a map() function, except it's built specifically for Pandas tables and series objects. For starters, you can think of series objects as array objects like NumPy. It is a one-dimensional indexed data table structure.

The apply() function applies a function to every element in a row or column you specify in a data table. Is it convenient? Especially if you need to format or modify all elements of a column, you don't have to loop over and over again!

Here are a few simple examples to familiarize you with basic grammar rules:

08. Pivot Tables

*** The most important is the pivot table. If you know anything about Microsoft Excel, you've probably used (or heard of)Excel's Pivot Table feature. Pandas has a pivot_table() function that does the same thing, formatting a data table and outputting it as an Excel worksheet. In practice, pivot tables will group data according to one or more keys, pass the function into the parameter aggfunc, the data will be counted according to the function you specify, and the results will be distributed to the table.

Here are some examples of pivot_table():

"What are the small details of using Python" is introduced here. Thank you for reading it. If you want to know more about industry-related knowledge, you can pay attention to the website. Xiaobian will output more high-quality practical articles for everyone!

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