Python用于具有矩阵值的列的矩阵由相应的列 [英] Python for matrix of a column with matrix value by a corresponding column

查看:46
本文介绍了Python用于具有矩阵值的列的矩阵由相应的列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这些数据,比如 d1:

I have these 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

我希望输出是这样的:

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

一个矩阵,其中的值是购买 Fruit1Fruit2 的不同人数.有人可以告诉我一种方法来做这个 Python.谢谢.

A matrix where the value being the number of distinct people who have taken Fruit1 and Fruit2. Can somebody tell me a way to do this Python. Thanks.

推荐答案

在不知道您的数据集是什么 type 的情况下,我会假设它是基于结构的元组列表你介绍的.

Without knowing what type your data set is, I'm going off the assumption that it's a list of tuples based on the structure you presented.

所以如果 fruit1 是一个元组列表,并且每个元组都包含水果的名称和人的 id.使用列表理解,您可以计算水果和人一起出现的次数,如下所示:

So if fruit1 is a list of tuples and each tuple contains the name of the fruit and the person's id. Using list comprehension, you can count the number of times the fruit and person appear together, like so:

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,依此类推...

As you can see fruit2 is a list of tuples, just like fruit1 with the addition of the number of occurrences for the fruit/person. So Person 1 had 1 entry or Banana, 2 for Mango, and so on...

它不完全是一个矩阵,但是,很难用所提供的信息更具体.

It's not exactly a matrix, however, it's hard to be more specific with the information provided.

这篇关于Python用于具有矩阵值的列的矩阵由相应的列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆