以特定比率将列表元素分发到新的 pandas DataFrame 列的更简单方法,条件是同一数据框的其他列值

Easier way for distributing elements of list to a new pandas DataFrame column in a specific ratio conditional on other column values of same dataframe

我有一个包含多列的 pandas DataFrame df。现在我想添加一个基于其他列值的新列。我在堆栈上找到了很多答案,包括 np.wherenp.select。但是,在我的例子中,对于每个 if 条件(每个 if/elif/else 块),新列必须在具有特定比率的 3 个值中进行选择。例如,

for i in range(df.shape[0]):
    if(df.iloc[i]['col1']==x):
        df.iloc[i]['new_col']= choose one value between l=['a','b','c'] in 0.3,0.3,0.4 ratio

即所有满足if语句条件的行,列表l的元素按上述比例分布到新列

尝试:

s = df['col1'] == x
df.loc[s, 'new_col'] = np.random.choice(['a','b','c'], 
                                        size=s.sum(), 
                                        p=[0.3,0.3,0.4])