简体   繁体   中英

Python 3.4 - Pandas - Rearranging rows based on value of one column of a Dataframe

I have a dataframe df1 in the form of:

ID  V1  V2  V3  V4
1   4  0.1 0.2  0.3
2   6  0.4 0.5  0.6
3   3  0.7 0.8  0.9
4   11 1.0 1.1  1.2
5   6  1.3 1.4  1.5

I would like to arrange rows with the ID column being odd, showing up at the top first, then the even ID values at the end.

Illustratively, I would like like to rearrange df1 in the format of:

 ID  V1  V2  V3  V4
 1   4  0.1 0.2  0.3 
 3   3  0.7 0.8  0.9
 5   6  1.3 1.4  1.5
 2   6  0.4 0.5  0.6
 4   11 1.0 1.1  1.2

Can anyone please point me to the best way to achieve this?'

EDIT/UPDATE

I used the ID column as a groupby() variable earlier. I notice that when I output my dataframe, the ID varilable technically isn't a column in the dataframe anymore. I want to perform the above functionality on the dataframe after I have used the groupby on ID. How can I convert the ID column that has been "groupby-ed" as a regular column in the dataframe?

Thank you.

Here is one approach (I didn't replicate all your columns, just to keep it shorter):

In [1]: df.loc[np.argsort(df.ID % 2 == 0)]
Out[1]: 
   ID  V1
0   1   4
2   3   3
4   5   6
1   2   6
3   4  11

As per OP's comment that 'ID' needs to be converted back to a column first before sorting, try:

df.reset_index(inplace=True)

Then my original solution should work, which is below:


One way is using a temporary column which tells you whether the row is odd or even:

df['odd_even'] = df['ID'] % 2  # result is 1 for odd IDs, 0 for even
df.sort_values(by=['odd_even', 'ID'], ascending=[False, True], inplace=True)
df.drop('odd_even', axis=1, inplace=True)

   ID  V1   V2   V3   V4
0   1   4  0.1  0.2  0.3
2   3   3  0.7  0.8  0.9
4   5   6  1.3  1.4  1.5
1   2   6  0.4  0.5  0.6
3   4  11  1.0  1.1  1.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM