1

Quick Summary:

need_to_reorder = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

I want to set an order for the need_to_reorder[0][x] x values using my sorting array

sorting_array = [1, 3, 0, 2]

Required result: need_to_reorder will equal

[['b', 'd', 'a', 'c'], [2, 4, 1, 3]] 

Searching for the answer, I tried using numPy:

import numpy as np
sorting_array = [1, 3, 0, 2]
i = np.array(sorting_array)
print i  ## Results: [1 3 0 2] <-- No Commas?
need_to_reorder[:,i]

RESULTS:

TypeError: list indicies must be integers, not tuple

I'm looking for a correction to the code above or an entirely different approach.

Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
Eric Hansen
  • 185
  • 1
  • 10
  • For input there is a csv file which is being read into a multidimensional array. Also, on input the client will give me instructions on how to reorder the data. There are some cleanup changes being made to some of the data. After the cleanup, I want to reorder the data and print the results. – Eric Hansen May 20 '15 at 20:06

3 Answers3

3

You can try a simple nested comprehension

>>> l = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]
>>> s = [1, 3, 0, 2]
>>> [[j[i] for i in s] for j in l]
[['b', 'd', 'a', 'c'], [2, 4, 1, 3]]

If you need this as a function you can have a very simple function as in

def reorder(need_to_reorder,sorting_array)
    return [[j[i] for i in sorting_array] for j in need_to_reorder]

Do note that this can be solved using map function also. However in this case, a list comp is preferred as the map variant would require a lambda function. The difference between map and a list-comp is discussed in full length in this answer

Community
  • 1
  • 1
Bhargav Rao
  • 50,140
  • 28
  • 121
  • 140
0
def order_with_sort_array(arr, sort_arr):
    assert len(arr) == len(sort_arr)
    return [arr[i] for i in sort_arr]

sorting_array = [1, 3, 0, 2]
need_to_reorder = [['a', 'b', 'c', 'd'], [1, 2, 3, 4]]

after_reordered =  map(lambda arr : order_with_sort_array(arr, sorting_array), 
                      need_to_reorder)
Pete Cacioppi
  • 880
  • 7
  • 11
0

This should work

import numpy as np
ntr = np.array([['a', 'b', 'c', 'd'], [1, 2, 3, 4]])
sa = np.array([1, 3, 0, 2])
print np.array( [ntr[0,] , np.array([ntr[1,][sa[i]] for i in range(sa.shape[0])])] )
>> [['a' 'b' 'c' 'd'],['2' '4' '1' '3']]
farhawa
  • 10,120
  • 16
  • 49
  • 91