将整列乘以随机数,并将其存储为新列。

2024-04-19 12:54:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个列有100行,我想从这个列生成多个列(比如100)。这些新列应该通过将第一列与随机值相乘来生成。有没有使用python的方法?我用excel试过了,但这是一个乏味的任务,因为每列我都要用一个随机生成的数字(randbetween(a,b))。在


Tags: 方法数字excelrandbetween
2条回答

您可以使用Numpy reshee将列与随机数相乘

a, b = 10 ,20
df = pd.DataFrame({'col':np.random.randint(0,500, 100)})
df['col'].values * np.random.randint(a, b, 100).reshape(-1,1)

要在数据帧中获得结果

^{pr2}$

假设您有一列数字数据:

import numpy as np
import random

# random.randint(a,b) will choose a random integer between a and b
# this will create a column that is 96 elements long
col = [random.randint(0,500) for i in range(96)]

现在,让我们利用支持向量标量乘法的numpy.array创建更多列:

^{pr2}$

现在,您可以通过循环添加新列

num_cols = 99

for i in range(num_cols): # or however many columns you want to add
    df[i] = df.x * random.randint(a,b)

df.head()
     x        0        1       2        3        4        5        6  ...      92      93      94       95       96       97      98       99
0   68   257040   214268  107576   266152   229568   309468   319668  ...   74460   25024   85952   320620   331840   175712   87788   254864
1  286  1081080   901186  452452  1119404   965536  1301586  1344486  ...  313170  105248  361504  1348490  1395680   739024  369226  1071928
2  421  1591380  1326571  666022  1647794  1421296  1915971  1979121  ...  460995  154928  532144  1985015  2054480  1087864  543511  1577908
3   13    49140    40963   20566    50882    43888    59163    61113  ...   14235    4784   16432    61295    63440    33592   16783    48724
4  344  1300320  1083944  544208  1346416  1161344  1565544  1617144  ...  376680  126592  434816  1621960  1678720   888896  444104  1289312

[5 rows x 101 columns]

相关问题 更多 >