python - Python - 如何根据字典对数组中的值进行排序和替换
问题描述
我创建了一个从不同文件中提取数据并将其插入到数组中的数组。该数据具有不同的值 1-7 和顺序。
即一个文件可以有3行
label1
label4
label3
下一个文件可能只有
label3
另一个可能有
label7
label1
label3
label2
我创建了一个字典
Dict = {1:'label1',
2:'label2',
3:'label3',
4:'label4',
5:'label5',
6:'label6',
7:'label7'}
我想要
- 遍历数组
- 将每个标签设置为字典值(即如果 label4 则它 =4)
- 按 1-7 的顺序订购
- 对于缺失值,在该位置放置一个 0
- 对于有值的点,在那个点上放一个 1
即对于[label1,label4,label3]
- 用字典值替换并排序——
[1,3,4]
- 循环遍历数组,如果该数字丢失,则在该位置放置一个 0,其他所有内容在它所在的同一位置变为 1 -
[1,0,1,1,0,0,0]
本质上,我是单热编码它。
这就是我正在尝试的,但我在某处弄乱了循环逻辑:
y_temp = []
for j in y:
for k in y[j]:
if y[j,k]== Dict[1]:
y_temp[k] = y_temp[k].append('1')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[2]:
y_temp[k] = y_temp[k].append('2')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[3]:
y_temp[k] = y_temp[k].append('3')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[4]:
y_temp[k] = y_temp[k].append('4')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[5]:
y_temp[k] = y_temp[k].append('5')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[6]:
y_temp[k] = y_temp[k].append('6')
else:
y[k] = y_temp[k].append('0')
elif y[j,k] == Dict[7]:
y_temp[k] = y_temp[k].append('7')
else:
y[k] = y_temp[k].append('0')
解决方案
您应该以另一种方式构建您的字典(即键应该是标签)。这将允许您将标签转换为索引。
要获得 1 和 0 的最终列表,您无需通过索引列表进行中间步骤,您可以直接从源数据构建该列表:
Dict = {'label1':1,
'label2':2,
'label3':3,
'label4':4,
'label5':5,
'label6':6,
'label7':7}
lines1 = """label1
label4
label3""".split("\n")
lines2 = """label3
label1""".split("\n")
lbl = [lines1,lines2] # <-- this is a list of lists (of strings) like yours
result = [0]+[0]*max(Dict.values())
for lineList in lbl:
for line in lineList:
result[Dict.get(line,0)] = 1 # <-- notice how this is using line, not lbl
result = result[1:]
print(result)
# [1, 0, 1, 1, 0, 0, 0]
推荐阅读
- javascript - 如何使用请求 API 从我的异步函数返回字符串?
- mysql - 谷歌云 SQL - MySQL 复制
- python - 如何使 pymysql 在查询我的 rds 数据库时不会挂起?
- javascript - 在Javascript中绘制多条三角形线
- javascript - 如何获取在(子)属性数组的项上过滤的对象数组的子集
- julia - Julia中模块和结构之间的名称冲突
- escaping - 如何转义从 jinja2 模板文件中读取的注释中的字符?
- python - Python:进程设置变量时未设置变量
- powershell - 为什么在使用 Get-Member 等 powershell 命令时不能使用命令替换而不是管道?
- python - 如何从python中坐标的DataFrame创建图形网络?