我有一个列表,我想根据所选的每个功能在网格中表达。
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/