4

I have a list of values. I have a dataframe where one of the columns contains the same values. How do I order dataframe same way list is ordered?

list example:

[3,
 4,
...
 21,
 23,
 25,
 26]

dataframe example:

     0   1    2
0   ND   3  0/1
1   ND   4  0/1
...
11  ND  21  0/1
12  ND  23  0/1
13  ND  25  0/1
14  ND  26  0/1

I need to make sure that table is ordered according to the list. Column I need to match is column 1 in the dataframe.

EDIT: replaced sort with order, because sort word is probably misleading

YKY
  • 2,493
  • 8
  • 21
  • 30
  • you need only the *make sure* it's ordered according to the list or do you need to actually order it according to it? (I think it's the latter, but it never hurts to ask) – TomCho Jun 17 '15 at 13:01
  • make sure that it is sorted according to the list. And if it is not sort it. – YKY Jun 17 '15 at 13:07
  • Are you looking for something like this: http://stackoverflow.com/questions/23279238/custom-sorting-with-pandas or http://stackoverflow.com/questions/13838405/custom-sorting-in-pandas-dataframe – EdChum Jun 17 '15 at 13:08
  • not really. I need to check if order in the list matches order in the column. And if it is not matching, order (probably sort is misleading word?) the table according to the list. – YKY Jun 17 '15 at 13:12

2 Answers2

5

You can create a dataframe based on your list, and merge with your dataframe

a = [3,4,1]
df_a = pd.DataFrame({'VAL2' : a})
df_b = pd.DataFrame({'VAL1' :[0,1,2,3,4,5,6]})
pd.merge(df_a, df_b,left_on='VAL2',right_on='VAL1',how='outer')
steboc
  • 1,161
  • 1
  • 7
  • 17
1

Maybe this:

df['order'] = df[1].apply(lambda v: l.index(v))
df_you_wanted = df.sort('order')[[0,1,2]]

Here l is your list, df is your dataframe.

hvedrung
  • 467
  • 4
  • 13