【问题标题】:Random selection in pandas dataframe熊猫数据框中的随机选择
【发布时间】:2016-06-04 15:42:20
【问题描述】:

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

给定df

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

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

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

谢谢

【问题讨论】:

    标签: python numpy pandas random


    【解决方案1】:
    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]
    

    【讨论】:

      【解决方案2】:

      无需使用单独的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
      

      【讨论】:

        猜你喜欢
        • 2020-12-09
        • 2023-01-14
        • 2017-08-21
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-14
        • 2014-09-02
        • 2019-06-29
        相关资源
        最近更新 更多