Home > Software engineering >  generating random values and append the results in next columns
generating random values and append the results in next columns

Time:06-08

The first thing I want to do is get four numbers from the user and put them in the first column.(For example: 10,30,60,80) Then I need to create another columns(second), in addition to the first column, and the rows of the second column should vary as shown below.

10  Values should range from 1-2
30 values should range from 3-4
60 values should range from 5-8
80 values should range from 3-8

Based on that I would like to generate 1000 data sets and save them as single file. Expected output should be similar

10   1.2  1.5 ...
30   3.8  3.4 ...
60   5.8  5.2 ...
80   3.8  4.2 ...

Script:

import numpy as np
import random
inp_data=[10, 30, 60, 80]
random_data=np.random.uniform(1,2)

I got stuck here, Please help experts.Thanks in advance.

CodePudding user response:

You can do this with pandas and numpy:

import pandas as pd
import numpy as np

inp_data=[10, 30, 60, 80]

# mapping dict for the ranges
ranges = {10: [1,2],
          30: [3,4],
          60: [5,8],
          80: [3,8]
         }

# initialize random generator
rng = np.random.default_rng()

# load input data as dataframe
df = pd.DataFrame(inp_data, columns=['inp_data'])
# apply random generator to input data column
random_df = df['inp_data'].apply(lambda x: rng.uniform(ranges[x][0], ranges[x][1], size=(1000))).apply(pd.Series)

# join generated data with df and save as csv
df = df.join(random_df)
df.to_csv('output.csv', index=False, header=False)
  • Related