我正在嘗試按兩列中的值對一個小的 df 進行排序,但我需要根據 B 列(操作)中的值對 A 列(價格)進行不同的排序順序(升序/降序)。
所以df看起來像這樣:
| 指數 | 價格 | 行動 |
|---|---|---|
| 4 | 0.9 | '賣' |
| 7 | 0.7 | '買' |
| 2 | 0.9 | '買' |
| 3 | 0.4 | '賣' |
| 6 | 0.6 | '賣' |
| 5 | 0.8 | '買' |
| 1 | 0.7 | '買' |
| 8 | 0.9 | '買' |
我目前的排序是通過熊貓:
tx_hist = tx_hist.sort_values(by=['dfindex', 'price'], ascending=[True, False], ignore_index=True)
我還嘗試了一個單獨的排序功能,它分別獲取“購買”價格,對它們進行排序并將它們重新插入 df,但我也無法使其按預期作業。
def sorttxhist(tx_hist):
for i in range(len(tx_hist)):
w = i
buytxs = []
selltx = []
if tx_hist['action'].iloc[w] == 'buy':
while tx_hist['action'].iloc[w] == 'buy':
print(buytxs)
buytxs.append(tx_hist['price'].iloc[w])
w = w 1
buytxs = buytxs.sort(reverse=True)
tx_hist['price'].iloc[i:w] = buytxs
#buytxs.clear()
elif tx_hist['action'].iloc[w] == 'sell':
while tx_hist['action'].iloc[w] == 'sell':
print(selltx)
selltx.append(tx_hist['price'].iloc[w])
w = w 1
selltx = selltx.sort(reverse=False)
tx_hist['price'].iloc[i:w] = selltx
print(type(selltx))
print(tx_hist)
return tx_hist
但它并沒有按照我的需要對其進行排序,這是按“dfindex”進行的第一次排序,對于“購買”(在“操作”列中)按降序(按價格)和升序進行第二次排序(價格方面)“賣出”(在“行動”列中)。
所以結果應該是這樣的:
| 指數 | 價格 | 行動 | 排序順序(不在df中) |
|---|---|---|---|
| 2 | 0.9 | '買' | 描述 |
| 1 | 0.7 | '買' | 描述 |
| 3 | 0.4 | '賣' | 升序 |
| 4 | 0.9 | '賣' | 升序 |
| 5 | 0.8 | '買' | - / 描述 |
| 6 | 0.6 | '賣' | - /升 |
| 8 | 0.9 | '買' | 描述 |
| 7 | 0.7 | '買' | 描述 |
任何幫助深表感謝!干杯
uj5u.com熱心網友回復:
使 2 列命名sort1并sort2用于排序
sort1團購和團售之間的列劃分
sort2購買組在列中有負價格
sort1然后按和排序sort2
(df
.sort_values('dfindex')
.assign(sort1=df1['action'].ne(df1['action'].shift(1)).cumsum())
.assign(sort2=df1['price'].mask(df1['action']=="buy", -df1['price']))
.sort_values(['sort1', 'sort2'])
)
下降前的輸出sort1和sort2
dfindex price action sort1 sort2
2 2 0.90 buy 1 -0.90
6 1 0.70 buy 1 -0.70
3 3 0.40 sell 2 0.40
0 4 0.90 sell 2 0.90
5 5 0.80 buy 3 -0.80
4 6 0.60 sell 4 0.60
7 8 0.90 buy 5 -0.90
1 7 0.70 buy 5 -0.70
最后下降sort1和sort2
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/529482.html
