Skip to main content
 首页 » 编程设计

python之Pandas 数据框中的随机选择

2024年10月24日8飞鱼

我正在尝试解决 this more complicated question .这是一个较小的问题:

给定 df

a    b 
1    2 
5    0 
5    9 
3    6 
1    8 

如何创建一个 C 列,它是同一行的 df['a'] 和 df['b'] 两个元素之间的随机选择?

因此,给定此虚拟 df,随机运算符将从 (1, 2) 对中选择第 1 行,从 (5, 0) 中选择第 2 行...等等。

谢谢

请您参考如下方法:

import random 
 
n = 2  # target row number 
random.sample(df.iloc[n, :2], 1)  # Pick one number from this row. 

对于整个数据框:

>>> df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1) 
0    [1] 
1    [5] 
2    [9] 
3    [3] 
4    [8] 
dtype: object 

清理它以提取单个值:

>>> pd.Series([i[0] for i in df.loc[:, ['a', 'b']].apply(random.sample, args=(1,), axis=1)], index=df.index) 
0    1 
1    5 
2    9 
3    3 
4    8 
dtype: int64 

或者利用“a”列的索引为零(假)而“b”列的索引为 1(真):

>>> [df.iat[i, j] for i, j in enumerate(1 * (np.random.rand(len(df)) < .5))] 
[1, 5, 5, 6, 8]