【问题标题】:creating a loop to go through different datasets with the same variable names to change values创建一个循环以遍历具有相同变量名称的不同数据集以更改值
【发布时间】:2020-04-20 05:46:14
【问题描述】:

我有 4 个数据集,分别命名为 cluster_1、cluster_2、cluster_3、cluster_4。我想循环遍历所有 4 个变量并将变量的值更改为二进制,因此如果它们大于或等于 1,则将其设置为 1,如果为 0,则将其设置为 0。所有数据集都有相同的变量名。

运行代码时,我不断收到错误“浮动”对象不可迭代。 binary 是变量名列表,clusti 是数据集列表。

    for i in binary:
        print(dataset[i])
        dataset[i] = dataset[i].apply(lambda x: [y if y== 0 else 1 for y in x]) ```


【问题讨论】:

  • 如果 dataset[i] 的输出是什么?
  • “数据集”的类型是什么? Python中没有内置这样的东西。如果您正在使用某些框架,请相应地标记您的问题。

标签: python loops


【解决方案1】:

尝试使用理解来执行此操作。

鉴于您上面的代码,dataset 的结构有两种不同的情况:

  1. 这是一个列表的列表,例如:

    数据集 = [ [0,1,2,3], [1,2,3,4], [0,0,2,1], [1,0,1,0] ]

  2. 它是列表的键控字典,例如:

    数据集 = { 'cluster_1': [0,1,2,3], 'cluster_2': [1,2,3,4], 'cluster_3': [0,0,2,1], 'cluster_4':[1,0,1,0] }

案例 1:如果您的数据集是列表列表,您可以使用列表推导式来做到这一点:

dataset = [[int(y != 0) for y in x] for x in dataset]

它的作用是创建一个列表列表:

  1. 外部列表推导 [█ for x in dataset]dataset 中的每个列表 x 评估为推导,
  2. 内部列表推导 [█ for y in x] 评估列表 x 中的每个值 y
  3. 表达式int(y != 0) 是三元表达式y if y== 0 else 1 的简化,因为三元在Python 中很笨重。如果 y == 0,y !=0 将产生布尔值 False,否则为 True。将其转换为 int() 将产生与三元逻辑相同的输出(0,如果 y 是 0,或者在所有其他情况下为 1)。

完整示例:

dataset = [
    [0,1,2,3], 
    [1,2,3,4], 
    [0,0,2,1], 
    [1,0,1,0]
]
dataset = [[int(y != 0) for y in x] for x in dataset]
print(dataset)

产量:

[[0, 1, 1, 1], [1, 1, 1, 1]]

CASE 2:如果dataset是一个字典,你可以使用字典推导:

dataset = {key: [int(y != 0) for y in val] for key, val in dataset.items()}

完整示例:

dataset = {
    'cluster_1': [0,1,2,3],
    'cluster_2': [1,2,3,4],
    'cluster_3': [0,0,2,1],
    'cluster_4': [1,0,1,0]
}
dataset = {key: [int(y != 0) for y in val] for key, val in dataset.items()}
print(dataset)

产量:

{'cluster_1': [0, 1, 1, 1], 'cluster_2': [1, 1, 1, 1], 'cluster_3': [0, 0, 1, 1], 'cluster_4': [1, 0, 1, 0]}

【讨论】:

  • 可能应该解释一下int(y != 0) 的作用,因为它并不明显。
  • int(y != 0) 的解释是一种改进,但是 - 很抱歉这么迂腐 - 一些代码 sn-ps 的格式丢失了,我不知道该怎么处理这些 @ 987654344@ 个字符。
  • @martineau 块字符代表被解释部分排除的其他代码。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-16
  • 1970-01-01
  • 2021-10-04
  • 2021-10-04
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多