代码之家  ›  专栏  ›  技术社区  ›  Mark K

熊猫从现有的每一行创建新行

  •  1
  • Mark K  · 技术社区  · 4 年前

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

    它现在所做的是,每一行、每一列都乘以一个介于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 回复  |  直到 4 年前
        1
  •  1
  •   BENY    4 年前

    random numpy random.choice

    np.random.choice(range(3,5),3)
    
        2
  •  1
  •   Quang Hoang    4 年前

    使用 np.random.randint(3,6, size=3) . 实际上,你可以马上做:

    df * np.random.randint(3,6, size=df.shape)
    
        3
  •  1
  •   Bill Huang    4 年前

    您也可以生成具有相同形状的乘法系数 df df * mul 和原版一样 测向 :

    .append() . 基准测试:使用此方法几乎可以立即完成10000行,而 .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]])