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

标签 python python-3.x pandas machine-learning

我有一个列表,我想根据所选的每个功能在网格中表达。

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

所需网格:

Index:   Apple   Banana   Yogurt   Oatmeal
1         "x"      "x"     " "       " "
2         "x"      " "     "x"       " "
3         " "      "x"     " "       "x"

我认为我需要通过网格使用正则表达式和字符串索引列表,如何做到这一点是我的问题。更好的是,是否有一个 python 库可以自动执行此操作(如 R 中的 Jumps/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 解决方案 - 首先创建 Series,然后通过 str[0] 选择列表的第一个值作为标量,最后一个 str.get_dummies :

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

df = pd.Series([','.join(x) for x in breakfast]).str.get_dummies(',')
print (df)
   Apple  Banana  Oatmeal  Yogurt
0      1       1        0       1
1      1       0        0       1
2      0       1        1       0

但如果可能的话,多个列表值的解决方案是列表理解,先join,然后str.get_dummies:

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

df = pd.Series([','.join(x) for x in breakfast]).str.get_dummies(',')
print (df)
   Apple  Banana  Oatmeal  Yogurt
0      1       1        0       1
1      1       0        0       1
2      0       1        1       0 

关于python - 基于字符串匹配打印列表的二维矩阵,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50274461/

相关文章:

python-3.x - 如何在Pandas中一次将多列数据类型格式转换为另一种数据类型格式,而又不提及列名称?

python - 将Python标签的特定宽度设置为这么多像素长?

python - 还记得上次函数调用的结果吗?

python - Pandas:如果包含超过 2 个条目,如何删除行?

pandas - 在 Pandas 中生成随机字符串

python - 如果不同数据帧的项目相等但尊重 Pandas 的条件,则打印值

python - 无法在 Windows 上导入 distutils.dir_util

python - 如何使用惩罚方法最小化违反约束的二次目标函数

python - openCV:尝试理解从相机代码捕获视频

python - Python 中是否可以换行注释?