Search code examples
pythonpandasnumpy

Automate initializing random integers for various columns in data frame Python


I am trying to minimize the following code to a for loop, as I have 14 of the similar columns, or something in a fewer number of code lines. What would be a pythonic way to do it?

df['fan1_rpm'] = np.random.randint(5675, 5725, 30)
df['fan2_rpm'] = np.random.randint(5675, 5725, 30)
df['fan3_rpm'] = np.random.randint(5675, 5725, 30)
df['fan4_rpm'] = np.random.randint(5675, 5725, 30)
.
.
.
.

Solution

  • So given you have 14 columns:

    n_cols = 14
    

    And assuming your column names follow the pattern implied:

    cols = [f"fan{i}_rpm" for i in range(1, n_cols + 1)]
    

    Then with pandas/numpy, you can simply:

    df[cols] = np.random.randint(5675, 5725, (30, n_cols))