【问题标题】:return the index using pandas series.sample()?使用 pandas series.sample() 返回索引?
【发布时间】:2017-08-30 19:42:51
【问题描述】:

我有一个熊猫系列,其中的值因几个不同的用户而异。我想做的是从每个用户那里随机抽取一个样本,并返回随机样本的索引值。

系列看起来像这样(每个用户出现在多行上):

index    
row1    user1
row2    user2
row3    user2
row4    user1
row5    user2
row6    user1
row7    user3
...

我写的函数是这样的:

def get_random_sample(series, sample_size, users):
""" Grab a random sample of size sample_size of the tickets resolved by each user in the list users.
    Series has the ticket number as index, and the username as the series values.
    Returns a dict {user:[sample_tickets]}
"""
    sample_dict = {}
    for user in users: 
        sample_dict[user] = series[series==user].sample(n=sample_size, replace=False) 

    return sample_dict

返回的内容如下:

# assuming sample_size is 4
{user1: [user1, user1, user1, user1],
 user2: [user2, user2, user2, user2],
...}

但我想得到的输出是:

{user1: [row1, row6, row32, row40],
 user2: [row3, row5, row17, row39],
...}
# where row# is the index label for the corresponding row.

基本上我想让 pandas series.sample() 返回随机样本项的索引而不是项值。不确定这是否可能,或者我是否最好先重组我的数据(也许将用户作为数据框中的系列名称,而索引成为该系列下的值?不知道该怎么做)。 任何见解都值得赞赏。

【问题讨论】:

    标签: python python-2.7 pandas series


    【解决方案1】:

    作为接受答案的@user48956 commented,使用numpy.random.choice对索引进行采样要快得多

    np.random.seed(42)
    df = pd.DataFrame(np.random.randint(0,100,size=(10000000, 4)), columns=list('ABCD'))
    %time df.sample(100000).index
    print(_)
    %time pd.Index(np.random.choice(df.index, 100000))
    
    Wall time: 710 ms
    Int64Index([7141956, 9256789, 1919656, 2407372, 9181191, 2474961, 2345700,
                4394530, 8864037, 6096638,
                ...
                 471501, 3616956, 9397742, 6896140,  670892, 9546169, 4146996,
                3465455, 7748682, 5271367],
               dtype='int64', length=100000)
    Wall time: 6.05 ms
    
    Int64Index([7141956, 9256789, 1919656, 2407372, 9181191, 2474961, 2345700,
                4394530, 8864037, 6096638,
                ...
                 471501, 3616956, 9397742, 6896140,  670892, 9546169, 4146996,
                3465455, 7748682, 5271367],
               dtype='int64', length=100000)
    

    【讨论】:

      【解决方案2】:

      让我们尝试在样本后使用.index 来返回这些样本的索引:

      sample_dict[user] = series[series==user].sample(n=sample_size, replace=False).index
      

      【讨论】:

      • 嗯,这比我预期的要简单。谢谢!
      • 嗯......看起来你应该能够做到:series[series==user].index.sample(n)。 series[series==user].sample(n) 不会创建不必要的中间系列吗? (遗憾的是索引上没有示例函数)。
      猜你喜欢
      • 1970-01-01
      • 2019-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-04-02
      • 2017-01-15
      • 2020-06-04
      相关资源
      最近更新 更多