Python for matrix column with matrix value corresponding column

I have this data, say d1:

Fruits  Person
Mango   1
Banana  1
Orange  2
Mango   1
Banana  3
Orange  1
Mango   2
Banana  3
Orange  2
Mango   2

I want the result to be something like this:

               Fruit2
Fruit1   Mango     Banana   Orange
Mango   2   0   2
Banana  0       
Orange

A matrix where the value is the number of individuals who have taken Fruit1and Fruit2. Can someone tell me a way to do this Python. Thank.

0
source share
1 answer

Not knowing what typeyour data set is, I assume that this is a list of tuples based on the structure you presented.

, fruit1 - , . , , , :

import itertools

fruit1 = [
    ('Mango', 1),
    ('Banana', 1),
    ('Orange', 2),
    ('Mango', 1),
    ('Banana', 3),
    ('Orange', 1),
    ('Mango', 2),
    ('Banana', 3),
    ('Orange', 2),
    ('Mango', 2),
]

# define sort order (person, fruit)
keyfunc = lambda t: (t[1], t[0])

# sort fruit1
fruit1.sort(key=keyfunc)

# create fruit2
fruit2 = [(len(list(val)), key) for (key, val) in itertools.groupby(fruit1, keyfunc)]

# output
[
    (1, (1, 'Banana')),
    (2, (1, 'Mango')),
    (1, (1, 'Orange')),
    (2, (2, 'Mango')),
    (2, (2, 'Orange')),
    (2, (3, 'Banana')),
]

, fruit2 - , fruit1 /. , Person 1 1 Banana, 2 Mango ...

, , .

0

Source: https://habr.com/ru/post/1649848/


All Articles