以特定比率将列表元素分发到新的 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.where
和 np.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
的元素按上述比例分布到新列
- 我目前的做法是,为每个
if-else
条件语句将 df
拆分为多个子数据帧 df_sub
。接下来使用 np.random.choices(l,df_sub.shape[0],p=[0.3,0.3,0.4)
where l=['a','b','c']
创建一个列表。将 l
添加到 df_sub
作为新列,然后沿着 axis=0
. 连接所有这些子数据框
- 我想知道是否有更简单的方法来完成此任务而不是分割和连接数据帧?
尝试:
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])
我有一个包含多列的 pandas DataFrame df
。现在我想添加一个基于其他列值的新列。我在堆栈上找到了很多答案,包括 np.where
和 np.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
的元素按上述比例分布到新列
- 我目前的做法是,为每个
if-else
条件语句将df
拆分为多个子数据帧df_sub
。接下来使用np.random.choices(l,df_sub.shape[0],p=[0.3,0.3,0.4)
wherel=['a','b','c']
创建一个列表。将l
添加到df_sub
作为新列,然后沿着axis=0
. 连接所有这些子数据框
- 我想知道是否有更简单的方法来完成此任务而不是分割和连接数据帧?
尝试:
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])