熊猫从每个现有行创建新行

时间:2020-10-25 00:06:37

标签: python pandas dataframe

一个简短的数据框,我想从现有行中创建新行。

现在要做的是,每一行,每一列乘以3到5之间的一个随机数:

import pandas as pd
import random

data = {'Price': [59,98,79],
'Stock': [53,60,60],
'Delivery': [11,7,6]}
df = pd.DataFrame(data)

for row in range(df.shape[0]):
    new_row = round(df.loc[row] * random.randint(3,5))
    new_row.name = 'new row'
    df = df.append([new_row])

print (df)



         Price  Stock  Delivery
0           59     53        11
1           98     60         7
2           79     60         6
new row    295    265        55
new row    294    180        21
new row    316    240        24

是否可能每行可以有多个不同的随机数?例如:

the 1st row 3 cells multiple (random) [3,4,5]
the 2nd row 3 cells multiple (random) [4,4,3] etc?

谢谢。

3 个答案:

答案 0 :(得分:1)

在您的for循环中将random更改为numpy random.choice

np.random.choice(range(3,5),3)

答案 1 :(得分:1)

使用np.random.randint(3,6, size=3)。实际上,您可以一次执行:

df * np.random.randint(3,6, size=df.shape)

答案 2 :(得分:1)

您还可以独立生成df形状相同的乘法系数,然后将按元素相乘的df * mul与原始df结合起来:

此方法避免了众所周知的缓慢.append()。基准:这种方法几乎立即完成10,000行,而.append()用了40秒!

import numpy as np
np.random.seed(111)  # reproducibility

mul = np.random.randint(3, 6, df.shape)  # 6 not inclusive
df_new = pd.concat([df, df * mul], axis=0).reset_index(drop=True)

输出:

print(df_new)
   Price  Stock  Delivery
0     59     53        11
1     98     60         7
2     79     60         6
3    177    159        33
4    294    300        28
5    395    300        30

print(mul)  # check the coefficients
array([[3, 3, 3],
       [3, 5, 4],
       [5, 5, 5]])
相关问题