Home > Software design >  Generate random float number in column as element
Generate random float number in column as element

Time:01-03

Is there any way I can generate random float array as element in 'Price' column?

import pandas as pd 
data = pd.read_csv("C:\\users\\Hp\\Downloads\\Stock.csv")
data = data.rename(columns={'Date': 'Exportation Date'})
data['Exportation Month'] = data['Exportation Date'].str[6:7] 

data['Price'] = 1.2

data.head()

Output (I deleted some columns due to large size that couldn't fit the question section):

Exportation Month   Price
0   2               1.2
1   6               1.2
2   1               1.2
3   8               1.2
4   8               1.2

Output I wanted (Assume those numbers in 'Price' are randomly generated):

Exportation Month   Price
0   2               5.4
1   6               2.5
2   1               4.4
3   8               17.1
4   8               2.3

CodePudding user response:

Assuming you want a price between 0 and 100 with 1 decimal, you can do it that way:

from random import uniform

data['Price'] = [round(uniform(0, 100), 1) for i in range(len(data))]

CodePudding user response:

I'd do something like this:

from random import randrange

randObj = f'{randrange(99)}.{randrange(99)}'
data['Price'] = float(randObj)

CodePudding user response:

You can just use numpy.random

import pandas as pd
import numpy as np

# Fake Data
df = pd.DataFrame({"a": [1, 2],
                   "b": [3, 4]})
# Add Price
df["Price"] = np.random.uniform(low=0, high=10, size=len(df))

# Eventually use 2 decimal places only.
df["Price"] = df["Price"].round(2)
  • Related