Tips for sharing Python data statistics

Source: Internet
Author: User
Recently in Python data statistics, here summarizes some recent use to find and summarize some of the tips, hoping to help in doing this when some of the children's shoes. Some techniques are very common usage and we don't notice them at ordinary times, but in certain scenarios, these small methods can be very helpful.

1. Map keys to multiple values in the dictionary

{' B ': [4, 5, 6], ' A ': [1, 2, 3]}

Sometimes when we are counting the same key value, we want to add all the same key entries to a dictionary with key, and then do all sorts of things, and then we can use the following code:

From collections Import DEFAULTDICTD = Defaultdict (list) print (d) d[' A '].append (1) d[' A '].append (2) d[' A '].append (3) d[' B '].append (4) d[' B '].append (5) d[' B '].append (6) print (d) Print (D.get ("a")) print (D.keys ()) print ([D.get (i) for i in D])

Here is the method used in collections, there are a lot of useful methods, we have time to continue in-depth understanding.

The above code runs the result:

Defaultdict (, {}) Defaultdict (, {' B ': [4, 5, 6], ' A ': [1, 2, 3]}) [1, 2, 3]dict_keys ([' B ', ' a ']) [[4, 5, 6], [1, 2, 3]]

After we fill in the data, it's equivalent to a quick grouping, and then iterating through each group to count the data we need.

2. Quickly convert dictionary key value pairs

Data = {...} Zip (Data.values (), Data.keys ())

Data is our format, using Zip for fast key-value conversions, and then using functions like max,min to manipulate data.

3. Sort dictionaries by public keys

From operator import Itemgetterdata = [  {' name ': ' Bran ', ' UID ': 101},  {' name ': ' Xisi ', ' UID ': 102},  {' name ': ' Land "," UID ": 103}]print (sorted (data, Key=itemgetter (" name ")) print (sorted (data, Key=itemgetter (" UID ")))

The data format, which we want to sort by name or UID, is the method in the code.
Operation Result:

[{' Name ': ' Bran ', ' UID ': 101}, {' name ': ' Land ', ' UID ': 103}, {' name ': ' Xisi ', ' UID ': 102}] [{' Name ': ' Bran ', ' UID ': 101}, {' name ': ' Xisi ', ' UID ': 102}, {' name ': ' Land ', ' UID ': 103}]

Just like we expected.

4. Group multiple dictionaries in a list according to a field

Note that the data is sorted first before grouping, and the sort fields are selected according to the actual requirements.

Data that will be processed:

rows = [  {' name ': ' Bran ', ' UID ': 101, ' class ': '-},  {' name ': ' Xisi ', ' UID ': 101, ' class ': one},  {' name ': ' Land ' , "UID": 103, "Class": 10}]

Expected processing results:

{101: [{' Name ': ' Xisi ', ' class ': One, ' uid ': 101},{' name ': ' Bran ', ' class ': ' UID ': 101}],103: [{' Name ': ' Land ', ' class ' : Ten, ' UID ': 103}]}

We group according to the UID, this is just a demonstration, the UID is generally not repeated.

This is a bit more complicated, and we're going to break it down one step

some = [(' A ', [1, 2, 3]), (' B ', [4, 5, 6])]print (Dict (some))

Results:

{' B ': [4, 5, 6], ' A ': [1, 2, 3]}

Our goal here is to convert tuples into dictionaries, which is very simple and should be understood. Then we'll take the next step to sort the processing data:

Data_one = sorted (rows, Key=itemgetter ("class")) print (data_one) Data_two = sorted (rows, Key=lambda x: (x["UID"], x[" Class "])) print (Data_two)

Here we provide two sort of the same principle, just slightly different style, the first kind of data_one is the direct use of itemgetter, according to our previous use, directly according to a field to sort, but sometimes we have another request:

Sort by a field first, and then sort by another field when the first field repeats.

In this case, we use the second method to sort the multiple-field values.
The sorting results are as follows:

[{' Name ': ' Land ', ' class ': Ten, ' UID ': 103}, {' name ': ' Xisi ', ' class ': One, ' UID ': 101}, {' name ': ' Bran ', ' class ': ' UID ' : 101}][{' name ': ' Xisi ', ' class ': One, ' UID ': 101}, {' name ': ' Bran ', ' class ': ' UID ': 101}, {' name ': ' Land ', ' class ': 10 , ' UID ': 103}]

As a result, we take a slow look, or slightly different.

The next step is to combine the two methods we just talked about using:

data = Dict ([(G, List (k)) for G, K in GroupBy (Data_two, Key=lambda x:x["UID"])] Print (data)

We grouped the sorted data, then generated a list of tuples, and finally turned it into a dictionary, where we succeeded in grouping the data.

Some tips for Python stats are shared here, and you can refer to learning as needed.

  • Related Article

    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.