[英]Python 3.4 - Pandas - Rearranging rows based on value of one column of a Dataframe
I have a dataframe df1 in the form of: 我有以下形式的数据框df1:
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. 我想排列ID列为奇数的行,首先显示在顶部,然后显示偶数ID值。
Illustratively, I would like like to rearrange df1 in the format of: 说明性地,我想以以下格式重新排列df1:
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 编辑/ UPDATE
I used the ID column as a groupby() variable earlier. 我之前使用ID列作为groupby()变量。 I notice that when I output my dataframe, the ID varilable technically isn't a column in the dataframe anymore.
我注意到,当我输出数据框时,从技术上讲可变ID不再是数据框中的一列。 I want to perform the above functionality on the dataframe after I have used the groupby on ID.
在ID上使用groupby之后,我想在数据帧上执行上述功能。 How can I convert the ID column that has been "groupby-ed" as a regular column in the dataframe?
如何将已“分组”的ID列转换为数据帧中的常规列?
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: 根据OP的评论,排序之前必须先将“ ID”转换回一列,然后尝试:
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.