![](/img/trans.png)
[英]How to do conditional sorting on a Pandas dataframe (i.e. ascending and descending order within one column based on values in another column)?
[英]Sorting values in one column that contains NAs by the order of another column
我在熊貓中有一個數據框
import pandas as pd
df=pd.DataFrame.from_dict({'col1':['A_2','A_1','A_3','A_4','A_6','A_5','A_8','A_7'],
'col2':['NaN','A_2','A_3','A_4','A_5','NaN','A_1','A_6']}, orient='index').T
我想更改第二列col2
的順序並更改它,以使兩列中相同的項目像這樣匹配:
col1 col2
0 A_2 A_2
1 A_1 A_1
2 A_3 A_3
3 A_4 A_4
4 A_6 A_6
5 A_5 A_5
6 A_7 NaN
7 A_8 NaN
嘗試: df.iloc[:,1].sort_values(df.iloc[:,0])
僅返回有關不可散列序列的錯誤消息
現在假設有兩個數據框:
DF1:
df1=pd.DataFrame({'col1':['A_2','A_1','A_3','A_4','A_6','A_5','A_8','A_7'],
'col2':[0,1,1,0,0,1,1,0], 'col3':[1,6,7,5,4,3,9,8]})
df2=pd.DataFrame({'N1':['NaN','A_2','A_3','A_4','A_5','NaN','A_1','A_6'],
'N2':['NaN',0,1,2,3,'NaN',0,1], 'N3':['NaN',0,0,0,0,'NaN',0,0]})
我想像上面那樣排序,但是這次, df2
所有列和行:
輸出:
N1 N2 N3
A_2 0 0
A_1 0 0
A_3 1 0
A_4 2 0
A_6 1 0
A_5 3 0
NaN NaN NaN
NaN NaN NaN
如果我理解正確的話,你可以重寫col2
與價值觀col1
當他們存在col2
:
df.col2 = df.col1[df.col1.isin(df.col2)]
結果:
df
Out[13]:
col2 col1
0 A_2 A_2
1 A_1 A_1
2 A_3 A_3
3 A_4 A_4
4 A_6 A_6
5 A_5 A_5
6 NaN A_8
7 NaN A_7
編輯 :擴展問題與兩個數據框
這隱含地假定df2.N1
中的值是唯一的( NaN
值除外)。 因此,我們可以將它們用作索引,以從N2
和N3
獲得相應的值。 然后,我們可以使用df1.col1
作為索引值:
In[53] : df2.set_index('N1', drop=False).loc[df1.col1]
Out[53]:
N1 N2 N3
N1
A_2 A_2 0 0
A_1 A_1 0 0
A_3 A_3 1 0
A_4 A_4 2 0
A_6 A_6 1 0
A_5 A_5 3 0
A_8 NaN NaN NaN
A_7 NaN NaN NaN
您始終可以添加.reset_index(drop=True)
來重置索引。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.