如何对.iterrows()值进行排序?

时间:2019-07-16 20:33:03

标签: python pandas numpy

我似乎找不到关于该主题的答案。我正在尝试对查询集中的值进行排序。现在,它会按TICKER_id自动排序:

TICKER_id
DXJ    -0.5
EWA     1.0
EWC     0.0
EWG    -1.0
EWI    -0.5
EWP    -0.5
EWQ     0.5
EWU     0.0
EWW    -0.5
EWY    -1.0
EWZ     0.5
EZA     0.5
FEZ    -0.5
INDA    0.0
MCHI   -0.5
RSX     0.5
SPY     0.0
TUR    -0.5

我觉得好像有一种方法可以使用.iterrows()遍历列表进行排序。

2 个答案:

答案 0 :(得分:0)

据我所知,Pandas使用索引来控制itterows,因此即使您使用了数据框,Pandas也将恢复到正常顺序,因为索引随行而行。

我已经能够按resetting the index的预期顺序遍历df:

#%%
import pandas as pd
import matplotlib.pyplot as plt

df = pd.DataFrame(
    [
        {"TICKER_id": "DXJ", "val": -0.5},
        {"TICKER_id": "EWA", "val": 1.0},
        {"TICKER_id": "EWC", "val": 0.0},
        {"TICKER_id": "EWG", "val": -1.0},
        {"TICKER_id": "EWI", "val": -0.5},
        {"TICKER_id": "EWP", "val": -0.5},
        {"TICKER_id": "EWQ", "val": 0.5},
        {"TICKER_id": "EWU", "val": 0.0},
        {"TICKER_id": "EWW", "val": -0.5},
        {"TICKER_id": "EWY", "val": -1.0},
        {"TICKER_id": "EWZ", "val": 0.5},
        {"TICKER_id": "EZA", "val": 0.5},
        {"TICKER_id": "FEZ", "val": -0.5},
        {"TICKER_id": "INDA", "val": 0.0},
        {"TICKER_id": "MCHI", "val": -0.5},
        {"TICKER_id": "RSX", "val": 0.5},
        {"TICKER_id": "SPY", "val": 0.0},
        {"TICKER_id": "TUR", "val": -0.5},
    ]
)

df.plot() # 1

#%%
df.sort_values(by="val", ascending=False, inplace=True)
df.reset_index(drop=True, inplace=True)
df.plot() # 2

#%%
for index, row in df.iterrows():
    if len(row.TICKER_id) == 3:
        plt.scatter(index,row.val, c="r")
    else:
        plt.scatter(index,row.val, c="b") # 3

这给出: 1. enter image description here 2. enter image description here 3. enter image description here

This question is related to this

答案 1 :(得分:-1)

也许您只需要.sort_values()

dat.sort_values()dat.sort_values(ascending=False)