在 Python 中为 2 个数据帧迭代 n 行

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

我有一个很大的训练和验证数据集。 有 40,000 行用于训练,40,000 行用于验证。但我不会一次使用整个数据集。 我想每 1000 行训练运行一次回归,做相应的预测 1000 行验证,然后计算误差,然后继续对接下来的 1000 行训练和验证执行相同的操作。 所以我重复这个过程40次。我如何在 Python 中执行此操作?

任何示例代码都会对我有很大帮助,因为我很迷茫。

我尝试使用 iterrows 进行 zip,但它不起作用。我知道 df.iterrows 可以帮助我遍历行,而 zip 将帮助我遍历两个数据帧的相应行,但是我该怎么做呢?

python loops zip iteration
1个回答
0
投票

您可以在每个

np.split(df, 40)
上使用
DataFrame
将它们分成40个部分。随后,您可以将
for loop
zip()
结合使用,以对
lists
DataFrames
执行并行迭代 - 请参见下面的代码:

import pandas as pd
import numpy as np

# example data
factor = 10_000
data = {
    'col_1': [1, 2, 3, 4] * factor,
    'col_2': [100, 200, 300, 400] * factor
}
training_df = pd.DataFrame(data)
validation_df = pd.DataFrame(data)
print(training_df.shape)  # (40000, 2)
print(validation_df.shape)  # (40000, 2)

# split DataFrame's into 40 parts - this gives you a list of dfs
training_dfs = np.split(training_df, 40)
validation_dfs = np.split(validation_df, 40)
print(training_dfs[0].shape)  # (1000, 2)
print(validation_dfs[-1].shape)  # (1000, 2)

# parallel iteration
for train_df, val_df in zip(training_dfs, validation_dfs):

    # train model on train_df
    # validate model on val_df
    # print metrics
    pass
© www.soinside.com 2019 - 2024. All rights reserved.