在pandas数据帧中随机选择

时间:2016-02-23 00:47:43

标签: python numpy pandas random

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

给定df

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

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

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

由于

2 个答案:

答案 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'索引为零(False)和列' b'索引为1(True):

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

答案 1 :(得分:0)

无需使用单独的random模块:

s = """a    b
1    2
5    0
5    9
3    6
1    8
"""

df = pd.read_table(StringIO(s),sep='\s+',engine='python')
df.apply(lambda x: x.sample(n=1).iloc[0],axis=1)
#output:
0    1
1    5
2    9
3    6
4    1
dtype: int64