繁体   English   中英

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

[英]“\” Line break makes pandas dataframe columns reorder alphabetically

我的代码太大了,所以我开始使用“ \\”以提高可读性。 但是,我注意到,这样做可以使我的列按字母顺序重新排序。

有谁知道如何阻止这种情况的发生?

这是代码:

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)

所以最后,df.columns返回了:

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

它应该返回:

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

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

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)

您可能还需要进行一些更改,删除一些多余的部分,但这只是要点。 [...]将保持东西放在一起,尽管他们之间的换行。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM