![](/img/trans.png)
[英]Python 3.4 - Pandas - Extract Rows Based on Column of another Dataframe Including Duplicates
[英]Python 3.4 - Pandas - Rearranging rows based on value of one column of a Dataframe
我有以下形式的數據框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
我想排列ID列為奇數的行,首先顯示在頂部,然后顯示偶數ID值。
說明性地,我想以以下格式重新排列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
誰能指出我實現這一目標的最佳方法?”
編輯/ UPDATE
我之前使用ID列作為groupby()變量。 我注意到,當我輸出數據框時,從技術上講可變ID不再是數據框中的一列。 在ID上使用groupby之后,我想在數據幀上執行上述功能。 如何將已“分組”的ID列轉換為數據幀中的常規列?
謝謝。
這是一種方法(我沒有復制所有列,只是為了使其更短):
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
根據OP的評論,排序之前必須先將“ ID”轉換回一列,然后嘗試:
df.reset_index(inplace=True)
然后,我的原始解決方案應該可以正常工作,如下所示:
一種方法是使用臨時列,該列告訴您該行是奇數還是偶數:
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.