我的代码太大了,所以我开始使用“ \”以提高可读性。但是我注意到,这样做可以使我的列按字母顺序重新排序。
有人知道如何阻止这种情况的发生吗?
代码如下:
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"]
答案 0 :(得分:1)
如果要以特定顺序显示相关列,请在输出中指定它们:
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)
您可能还需要进行一些其他更改,删除一些多余的部分,但这只是要点。尽管[...]
之间保持了换行符,但它们仍将保持在一起。