Home > Mobile >  numpy/pandas - why the selected the element from list are the same by random.choice
numpy/pandas - why the selected the element from list are the same by random.choice

Time:12-20

there is a list which contains integer values. list=[1,2,3,.....] then I use np.random.choice function to select a random element and add it to the a existing dataframe column, please refer to below code

df.message = df.message.astype(str)   "rowNumber="   '"'   str(np.random.choice(list))    '"'

But the element selected by np.random.choice and appended to the message column are always the same for all message row.

What is issue here?

Expected result is that the selected element from the list is not the same.

CodePudding user response:

Pass to np.random.choice with parameter size and convert values to strings:

df = pd.DataFrame(
    {'message' : ['aa','bb','cc']})

L = [1,2,3,4,5]
df.message = (df.message.astype(str)   "rowNumber="   '"'   
                np.random.choice(L, size=len(df)).astype(str)    '"')
print (df)
           message
0  aarowNumber="4"
1  bbrowNumber="2"
2  ccrowNumber="5"
  • Related