This article was first published on Zhihu

This paper is divided into the following parts

  • The list of transpose
  • The dictionary transpose
  • Conversion between dictionary lists
  • conclusion

The list of transpose

existing

l = [['a'.'b'.'c'],
     [1, 2, 3]]
Copy the code

Want to get

[('a', 1), ('b', 2), ('c'And 3)]Copy the code

The following code

[z for z in zip(*l)]
Copy the code

The basic usage of the zip function, which plays an important role in the transpose of list, is as follows

for z in zip(['a'.'b'.'c'], [1, 2, 3]) :print(z)

# output
('a'(1),'b'And (2)'c', 3)
Copy the code

Dictionary transpose

existing

m = {'Bob': {'age': 30.'country': 'America'},
     'Mary': {'age': 20.'country': 'China'},
     'Frank': {'age': 25.'country': 'America'}}
Copy the code

Want to get

{'age': {'Bob': 30.'Frank': 25.'Mary': 20},
 'country': {'Bob': 'America'.'Frank': 'America'.'Mary': 'China'}}
Copy the code

Transpose pandas

>>> m = {'Bob': {'age': 30.'country': 'America'},...'Mary': {'age': 20.'country': 'China'},...'Frank': {'age': 25.'country': 'America'}}
>>>
>>> import pandas as pd
>>> pd.DataFrame(m)
             Bob    Frank   Mary
age           30       25     20
country  America  America  China
>>> pd.DataFrame(m).transpose()
      age  country
Bob    30  America
Frank  25  America
Mary   20    China
>>> pd.DataFrame(m).transpose().to_dict()
{'age': {'Mary': 20.'Bob': 30.'Frank': 25}, 'country': {'Mary': 'China'.'Bob': 'America'.'Frank': 'America'}}
Copy the code

We can do that if we use the knowledge of the dictionary alone

from collections import defaultdict
result = defaultdict(dict)
for names, infos in m.items():
    for k, v in infos.items():
        result[k].update({names: v})
        
dict(result)
Copy the code

Conversion between dictionary lists

existing

d = {'name': ['a'.'b'.'c'].'num': [1, 2, 3]}
Copy the code

Want to get

[('a', 1), ('b', 2), ('c'And 3)] [{'name': 'a'.'num': 1}, 
 {'name': 'b'.'num': 2},
 {'name': 'c'.'num': 3}]
Copy the code

Two forms

The following code

# the first
[z for z in zip(*d.values())]

# the second
[dict(zip(d.keys(), z)) for z in zip(*d.values())]
# or
[dict(zip(d, z)) for z in zip(*d.values())]
Copy the code

conclusion

Let’s start by looking at what forms of data we encountered

{'name' : ['a'.'b'.'c'].'num' : [1, 2, 3]}
 
{'Bob': {'age': 30.'country': 'America'},
 'Mary': {'age': 20.'country': 'China'},
 'Frank': {'age': 25.'country': 'America'}}
 
{'age': {'Bob': 30.'Frank': 25.'Mary': 20},
 'country': {'Bob': 'America'.'Frank': 'America'.'Mary': 'China'}}
 
[('a', 1), ('b', 2), ('c'And 3)] [{'a', 1}, {'b', 2}, {'c', 3}]
[{'a': 1}, {'b': 2}, {'c': [{3}]'name': 'Bob'.'age': 30.'country': 'America'},
 {'name': 'Mary'.'age': 20.'country': 'China'},
 {'name': 'Frank'.'age': 25.'country': 'America'}]
Copy the code

Here’s a summary of the ideas for looking at dictionary lists

  • First, and most important, is the structure of lists, which treat sets and tuples as lists (unordered and so on are minor details)
  • Dictionaries, on the other hand, can be thought of as special lists, that is, lists with names for each element, keys for names, and values for the elements of the list

The reader can use this idea to look at the data above and see why some of the data can be directly converted to a data box using pd.dataframe, which is equivalent to a matrix formed by a two-dimensional list. A dimension that is considered a row if presented as a list and a column if presented as a dictionary.

In converting these data to each other, just remember a few routines according to the form of results to be generated:

1. If the result is a dictionary, simply use dictionary generators, etc. When values are dynamically updated, they are typed using defaultdict in the Collections module, and the data is looped in, append if the value type is list, and Update if dict.

Note: Sometimes the result is that dictionaries specify keys manually, values are obtained directly using list generators, etc. This is less common, because you can’t modify it to be a function for all situations if you need to specify keys manually.

2. If the result is a list, use the list generator to construct the form of each element

3. When it comes to transposes, which are essentially list transposes, think zip, and sometimes defaultdict

Welcome to my zhihu column

Column home: Programming in Python

Table of contents: table of contents

Version description: Software and package version description