1

I have dataframe whose one column is cost column and it's data goes from negative to positive values. Ex:-

1,0,-2,3,-2,5,1,-4,0

I want it to be sorted like 0,0,1,1,3,5,-2,-2,-4 Same valued column can be kept in order of their encounter.

So basic sorting should be done so that we have positive values in ascending and then negative in descending.

I don't want to copy or create new dataframe because I'll sort dataframe and pick a row based on cost and delete it and then again sort by changing cost factor.

1
  • Problem solved?? Commented Feb 23, 2021 at 15:11

2 Answers 2

2

Assuming this to be your df:

In [312]: l = [1,0,-2,3,-2,5,1,-4,0]
In [315]: df = pd.DataFrame(l, columns=['a'])

In [316]: df
Out[316]: 
   a
0  1
1  0
2 -2
3  3
4 -2
5  5
6  1
7 -4
8  0

Use pd.concat with df.sort_values:

In [327]: mask = df['a'].ge(0) # Get all values which are >= 0

# sort positive and negative values separately, and then concat both
In [329]: df['a'] = pd.concat([df[mask].sort_values('a'), df[~mask].sort_values('a', ascending=False)], ignore_index=True) 

In [330]: df
Out[330]: 
   a
0  0
1  0
2  1
3  1
4  3
5  5
6 -2
7 -2
8 -4
Sign up to request clarification or add additional context in comments.

2 Comments

Could you please explain this....pd.concat([df[mask].sort_values('a', ascending=True), df[~mask].sort_values('a', ascending=False)], ignore_index=True)
@Brainiac I've put explanation in comments. Please check.
1

Method 1:

using sort_values:

df = pd.concat((df.cost[df.cost >= 0].sort_values(), df.cost[df.cost < 0].sort_values(ascending=False)))

Method 2:

Pythonic way:

so = sorted([1,0,-2,3,-2,5,1,-4,0], key=lambda x: (x<0, abs(x)))

so

[0, 0, 1, 1, 3, 5, -2, -2, -4]

Complete Solution:

li = [1,0,-2,3,-2,5,1,-4,0]
df = pd.DataFrame(li, columns=['cost'])
so = sorted(df.cost, key=lambda x: (x<0, abs(x)))
sorterIndex = dict(zip(so, range(len(so))))
df = df.sort_values(by=['cost'], key=lambda x: x.map(sorterIndex))

df:

cost
1   0
8   0
0   1
6   1
3   3
5   5
2   -2
4   -2
7   -4

4 Comments

How can it be used for Dataframe, I'm guessing this is for array
My dataframe have other columns too and when I tried sort method it only copied cost column and dropped or deleted or ignored other columns.
@Brainiac: Use second solution then
Yes, made few changes in first solution only and hopefully it's working.. here's the code ` df = pd.concat((df[df['cost'] >= 0].sort_values(by=['cost']), df[df['cost'] < 0].sort_values(by=['cost'],ascending=False))) ` and then reindexed for cleaner format.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.