【问题标题】:Python function does not call given argument for every iteration in inner loopPython函数不会为内部循环中的每次迭代调用给定的参数
【发布时间】:2019-03-16 13:43:55
【问题描述】:

我已经写了这段代码:

class_1500_strings = ['transistor', 'resistor', 'diode', 'processor', 'thermistor', '555-timer', 'microcontroller']

class_1500 = {'conductivity' : gaussian_sample(100, 10, 250),
              'price_per_unit' : gaussian_sample(10, 2, 250),
              'number_bought' : categorical_sample(0, 10, 250),
              'manufacturer' : string_sample(250, class_1500_strings),
              'acquisition_date' : date_random_sample("1/1/2008 1:30 PM", "1/1/2009 4:50 AM", col_length=250),
              'runtime' : gaussian_sample(1000, 200, 250)

def generate_table(class_dict, class_label, number_of_samples):
    X, y = [], []
    for table_idx in range(number_of_samples):
        df = pd.DataFrame(class_dict)
        label = class_label
        X.append(df)
        y.append(label)
    return X, y

X, y = generate_table(class_1500, 0, 5)

目的是构建样本人工数据框。我遇到的问题是 X 是相同数据帧的列表,而不是在类字典中调用随机生成器。如何使函数生成不同数据集的列表(即每次运行循环时调用采样器)?

【问题讨论】:

    标签: python python-3.x function dictionary for-loop


    【解决方案1】:

    您需要为您构建的每个数据框创建一个新字典。使用您当前的逻辑,一旦定义了class_1500,它就失去了与随机生成器逻辑的所有联系,因为这些值都是类似数组的。

    一种方法是定义一个单独的函数,每次运行时给出不同的数组:

    def make_data():
         return {'conductivity' : gaussian_sample(100, 10, 250),
                 ...
                 'runtime' : gaussian_sample(1000, 200, 250)}
    
    def generate_table(class_label, number_of_samples):
        X, y = [], []
        for table_idx in range(number_of_samples):
            df = pd.DataFrame(make_data())
            label = class_label
            X.append(df)
            y.append(label)
        return X, y
    
    X, y = generate_table(0, 5)
    

    【讨论】:

      【解决方案2】:

      您在循环的每次迭代 (class_dict) 中使用相同的值构造一个 DataFrame。如果您希望每次迭代的 DataFrame 值都不同,则必须提供不同的值。尝试将您的 for 循环更新为 for key in class_dict,对于 DataFrame 的参数,提供 key

      这样一来,您的字典的每个键都有一个 DataFrame,其中 DataFrame 的值由字典键的值(示例函数)生成。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-11-21
        • 2013-04-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多