我有這段代碼可以對 DataFrame 進行一些分析。both_profitable是True當且僅當該行中的long_profitable和都是。但是,DataFrame 非常大,并且使用 pandas比我想要的更費力。short_profitableTrueapplyaxis=1
output["long_profitable"] = (
df[[c for c in df.columns if "long_profit" in c]].ge(target).any(axis=1)
)
output["short_profitable"] = (
df[[c for c in df.columns if "short_profit" in c]].ge(target).any(axis=1)
)
output["both_profitable"] = output.apply(
lambda x: True if x["long_profitable"] and x["short_profitable"] else False,
axis=1,
)
是否有更簡單/更優化的方法來實作同樣的目標?
uj5u.com熱心網友回復:
您應該eq在列上使用方法:
output["both_profitable"] = output["long_profitable"].eq(output["short_profitable"])
或者由于兩列都是布林值,您可以使用按位運算&符:
output["both_profitable"] = output["long_profitable"] & output["short_profitable"]
另外僅供參考,您可以使用str.contains loc代替串列推導來選擇以df下列:
output["long_profitable"] = df.loc[:, df.columns.str.contains('long_profit')].ge(target).any(axis=1)
output["short_profitable"] = df.loc[:, df.columns.str.contains('short_profit')].ge(target).any(axis=1)
uj5u.com熱心網友回復:
both_profitable是True當且僅當該行中的long_profitable和都是short_profitableTrue
換句話說,both_profitable是兩列上布爾與的結果。
這可以通過多種方式實作:
output['long_profitable'] & output['short_profitable']
# for any number of boolean columns, all of which we want to AND
cols = ['long_profitable', 'short_profitable']
output[cols].all(axis=1)
# same logic, using prod() -- this is just for fun; use all() instead
output[cols].prod(axis=1).astype(bool)
當然,您可以將上述任何內容分配給新列:
output_modified = output.assign(both_profitable=...)
注意:如果您對許多列進行 AND 運算,則第 2 和第 3 形式特別有趣。
定時
n = 10_000_000
np.random.seed(0)
output = pd.DataFrame({
'long_profitable': np.random.randint(0, 2, n, dtype=bool),
'short_profitable': np.random.randint(0, 2, n, dtype=bool),
})
%timeit output['long_profitable'] & output['short_profitable']
# 4.52 ms ± 41.4 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output[cols].all(axis=1)
# 18.6 ms ± 53 μs per loop (mean ± std. dev. of 7 runs, 100 loops each)
%timeit output[cols].prod(axis=1).astype(bool)
# 71.6 ms ± 375 μs per loop (mean ± std. dev. of 7 runs, 10 loops each)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/435566.html
上一篇:根據另一個中的條件選擇列中的值
