Google colabs 说索引超出范围,而本地机器则不然

问题描述 投票:0回答:1

我一直在尝试使用google colabs tensorflow来编译我的一个项目。在我的本地计算机上使用较低的样本(1000 等)进行编译没有问题,但编译所有实例(42000)时花费的时间太长。

def str_column_to_float(dataset, column):
    for row in dataset:
        value = row[column]
        if isinstance(value, str):  # Check if the value is a string
            value = value.strip()
            if not value.replace('.', '').isdigit():  # Check if the value is not numeric
                continue
        try:
            row[column] = float(value)
        except (ValueError, AttributeError):
            pass  # Skip conversion for non-numeric values

这是函数调用

filename = 'Train_data.csv'
dataset = load_csv(filename)
dataset = dataset[1:]
  for i in range(0, len(dataset[0]) - 1):
          str_column_to_float(dataset, i)

我没有发现任何问题,也不明白为什么这只发生在 colabs 中并且在 vscode 上运行良好我什至尝试指定其中包含文字的列,但无济于事 `

def str_column_to_float(dataset, column):
    for row in dataset:
        row[column] = float(row[column].strip())
for i in range(0, len(dataset[0])-1):
    if i not in [1, 2, 3, 42]:  # Skip conversion for columns 1, 2, 3, and 42
        str_column_to_float(dataset, i)
python google-colaboratory
1个回答
0
投票

假设您正在使用 Pandas 或类似的库,您可能可以通过使用内置向量运算来避免很多痛苦

filename = 'Train_data.csv'
dataset = load_csv(filename)
dataset = dataset[1:]

for column in dataset.columns:             # ignores index
    s_tmp = dataset[column]                # column Series
    s_tmp = s_tmp.astype(float)            # coerce to floats and NaN
    s_tmp = s_tmp.fillna(dataset[column])  # NaN to original value
    dataset[column] = s_tmp                # clobber with new data

请注意,这可能会导致列中出现混合数据,这是最初会发生的情况,但应该是不可能的或不受欢迎的

如果您不确定哪些整列都是非数字的,而某些字符串列可能是浮点数,则只需检查是否有 NaN 并跳过这些

    ...
    s_tmp = s_tmp.astype(float)
    if any(s_tmp.isna()):  # at least one value is NaN (non-float)
        continue  # don't coerce column

最后,您可能会发现您可以按照此处所述的更好的方式完全保存和加载数据将导入的 .csv 中的字符串更改为浮点数

© www.soinside.com 2019 - 2024. All rights reserved.