按列排序和选择,同时将原始索引保留在python中

时间:2018-11-27 20:00:45

标签: python python-3.x pandas numpy

说我有三列,分别为名称“ a”,“ b”和“ c”。三列中的所有值都具有不同的范围并且是随机的。

我想做的是:

  1. 保留行索引。
  2. 选择列“ a”。将列“ a”中的值从最小到最大排序。
  3. 将已排序的列“ a”切片为某些部分。例如,从最小值到最大值的1/3,从1/3到2/3,从2/3到最大值。这总共是三个部分。
  4. 在每个部分中随机选择三行。
  5. 排除选择的行的原始索引,这样我就不再选择相同的行。
  6. 对列“ b”和“ c”重复1.至5.。

有简单的方法吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

与其以“行”和“列”的方式来考虑,不等的方式是将问题视为三个单独的数字列表,将每个列表分成3组,然后从每个列表中选择3个数字9组,这样它们的索引位置不会在3个列表的任何一个中重复(例如,如果我们最终在列表'a'的第二个块的第6个位置中选择数字,那么我们就无法选择该数字在列表“ b”或“ c”的第二个块中的第六个位置。

您可以使用numpy.array_split将列表分成3个大致相等的部分。 random模块为您提供了方便的random.sample()函数,然后您可以从每个集合中选择3个随机数字,总共9个数字。但是不幸的是,由于我们需要跟踪所使用的索引号,因此必须将其考虑在内。这是一种方法:

import random
import numpy

def process_list(original_list, exclude_indices):
    # Sort the list
    original_list.sort()

    # Split the list into a list of 3 sublists, each about the same size
    mylist_split = [arr.tolist() for arr in numpy.array_split(original_list, 3)]

    # Go through each sublist, checking the corresponding list of indices in exclude_indices
    number_choices = [ ]
    for i in range(3):
        # Look at each chunk of numbers in mylist_split.  If the length is n, then generate
        # a random list of numbers between 0 and n-1 (inclusive), EXCLUDING any index numbers
        # found in exclude_indices[i].
        possible_positions = [ j for j in range(len(mylist_split[i])) if j not in exclude_indices[i] ]

        # Pick 3 random index numbers of what's available.  Then pick the corresponding
        # numbers in those positions.
        chosen_indices = random.sample(possible_positions, 3)
        for k in chosen_indices:
            number_choices.append(mylist_split[i][k])

        # Update exclude_indices[i] to keep track.
        exclude_indices[i] += chosen_indices

    return number_choices, exclude_indices


# Generate some random lists of numbers to work with
length = 50    
a = [int(100*random.random()) for i in range(length) ]
b = [int(100*random.random()) for i in range(length) ]
c = [int(100*random.random()) for i in range(length) ]

exclude_indices = [ [], [], [] ]
a_choices, exclude_indices = process_list(a, exclude_indices)
b_choices, exclude_indices = process_list(b, exclude_indices)
c_choices, exclude_indices = process_list(c, exclude_indices)

print("a is", a)
print("Chosen numbers: ", a_choices)
print("b is", b)
print("Chosen numbers: ", b_choices)
print("c is", c)
print("Chosen numbers: ", c_choices)
相关问题