“\”换行符使数据帧列按字母顺序重新排序

2024-04-19 09:16:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我的代码太大了,所以我开始用“\”来提高可读性。不过,我注意到,通过这样做,我的列按字母顺序重新排序。你知道吗

有人知道如何阻止这种事情发生吗?你知道吗

代码如下:

def unsettled_event(team_name,market):
    """Returns all bets tied to this specific event."""
    combos_list = df[(df["home"] == team_name) \
                     & (df["profit"].isnull()) \
                     & (df["market"] == market) \
                     & (df['settled_date']).isnull()].combo_id.dropna().unique()
    df_combos = df[df["combo_id"].isin(combos_list)].sort_values("combo_id") \
                [["combo_id", "home", "market", "odds", "selection", "bookmaker", "broker", "stake_adj", "is_won"]] 
    df_singles = df[(df["home"] == team_name) \
                    & (df["leg_size"] == 1) \
                    & (df["profit"].isnull()) \
                    & (df["market"] == market) \
                    & (df['settled_date']).isnull()] \
                [["combo_id", "home", "market", "selection", "odds", "bookmaker", "broker", "stake_adj", "is_won"]]
    return pd.concat([df_singles, df_combos], ignore_index=True)

所以最后,测向列正在返回:

['bookmaker', 'broker', 'combo_id', 'home', 'is_won', 'market', 'odds', 'selection', 'stake_adj']

它应该返回:

["combo_id", "home", "market", "selection", "odds", "bookmaker", "broker", "stake_adj", "is_won"]

Tags: iddfhomeisbrokermarketcombowon
1条回答
网友
1楼 · 发布于 2024-04-19 09:16:29

如果希望相关列按特定顺序显示,请在输出中指定它们:

df[["combo_id", "home", "market", "selection", "odds", "bookmaker", 
    "broker", "stake_adj", "is_won"]].head()

在引擎盖下,顺序无关紧要。如果它在输出中很重要,你最好说清楚。你知道吗

(请注意,有一半以上的时间,它在输出中也不重要。)


你也不需要反斜杠。你知道吗

例如,这很好,而且更具Python风格:

def unsettled_event(team_name,market):
    """Returns all bets tied to this specific event."""
    columns = ["combo_id", "home", "market", "selection", "odds",
               "bookmaker", "broker", "stake_adj", "is_won"]
    combos_list = df[(df["home"] == team_name)
                     & (df["profit"].isnull())
                     & (df["market"] == market)
                     & (df['settled_date']).isnull()].combo_id.dropna().unique()
    df_combos = df[df["combo_id"].isin(combos_list)].sort_values("combo_id")[columns]     
    df_singles = df[(df["home"] == team_name)
                    & (df["leg_size"] == 1)
                    & (df["profit"].isnull())
                    & (df["market"] == market)
                    & (df['settled_date']).isnull()][columns]
    return pd.concat([df_singles, df_combos], ignore_index=True)

可能还有一些变化,你可以做,删除一些多余的部分,但这是它的要点。尽管有新的东西,它们还是会在一起。你知道吗

相关问题 更多 >