基于字符串匹配打印列表的二维矩阵

我有一个列表,我想根据每个选定的特征将其以网格形式表达出来。

breakfast = [['Apple,Banana'],['Apple,Yogurt'],['Banana,Oatmeal']]

期望的网格:

Index:   Apple   Banana   Yogurt   Oatmeal1         "x"      "x"     " "       " "2         "x"      " "     "x"       " "3         " "      "x"     " "       "x"

我想我需要使用正则表达式和列表的字符串索引来通过网格进行操作,这是我的问题所在。更好的方法是,有没有一个Python库可以自动完成这个操作(就像R中的leaps/summary)?

这是我目前的代码:

def printMatrix(data):    header = "Index:\tApple\tBanana\tYogurt\tOatmeal"    print(header)    for index, value in enumerate(data):        if str(value).find('Apple') != -1:            print(index,"\t\'X'", end='')        else:            print(index,"\t\' '",end='')        if str(value).find('Banana') != -1:            print("\t\'X'", end='')        else:            print("\t\' '",end='')        if str(value).find('Yogurt') != -1:            print("\t\'X'", end='')        else:            print("\t\' '")        if str(value).find('Oatmeal') != -1:            print("\t\'X'")

结果是准确的,但效率感觉很差。


回答:

集合、列表推导式与三元条件表达式加上 Pandas

如果你想要既Pythonic又美观,这里是一种方法。

import pandas as pdbreakfast = [['Apple,Banana'],['Apple,Yogurt'],['Banana,Oatmeal']]breakfast = [i[0].split(',') for i in breakfast]columns=list(set([j for i in breakfast for j in i]))columns.sort()values = [[1 if j in i else 0 for j in columns]for i in breakfast]df = pd.DataFrame(values, columns=columns)print(df) 

   Apple  Banana  Oatmeal  Yogurt0      1       1        0       01      1       0        0       12      0       1        1       0

Related Posts

L1-L2正则化的不同系数

我想对网络的权重同时应用L1和L2正则化。然而,我找不…

使用scikit-learn的无监督方法将列表分类成不同组别,有没有办法?

我有一系列实例,每个实例都有一份列表,代表它所遵循的不…

f1_score metric in lightgbm

我想使用自定义指标f1_score来训练一个lgb模型…

通过相关系数矩阵进行特征选择

我在测试不同的算法时,如逻辑回归、高斯朴素贝叶斯、随机…

可以将机器学习库用于流式输入和输出吗?

已关闭。此问题需要更加聚焦。目前不接受回答。 想要改进…

在TensorFlow中,queue.dequeue_up_to()方法的用途是什么?

我对这个方法感到非常困惑,特别是当我发现这个令人费解的…

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注