3 回答

TA貢獻(xiàn)1921條經(jīng)驗(yàn) 獲得超9個(gè)贊
np.select根據(jù)您給它選擇的那些條件,使用您傳遞條件列表的哪個(gè),并且您可以在不滿足任何條件時(shí)指定默認(rèn)值。
conditions = [
(d.entity == 10) & (d.value != 1000) & (d.location == 'CA'),
(d.entity != 10) & (d.entity != 0) & (d.value == 1000) & (d.location == 'US'),
(d.entity == 0) & (d.value == 1000) & (d.location == 'US')
]
choices = ["A", "C", "B"]
df['flag'] = np.select(conditions, choices, default="Different case")

TA貢獻(xiàn)1936條經(jīng)驗(yàn) 獲得超7個(gè)贊
添加()按位and->&用于處理numpy.select:
m = [
(d.entity == 10) & (d.value != 1000) & (d.location == 'CA'),
(d.entity != 10) & (d.entity != 0) & (d.value == 1000) & (d.location == 'US'),
(d.entity == 0) & (d.value == 1000) & (d.location == 'US')
]
df['flag'] = np.select(m, ["A", "C", "B"], default="Different case")

TA貢獻(xiàn)1946條經(jīng)驗(yàn) 獲得超4個(gè)贊
您寫了“查找滿足一組條件的所有列”,但您的代碼顯示您實(shí)際上是在嘗試添加一個(gè)新列,其每行的值是根據(jù)同一行的其他列的值計(jì)算的。
如果確實(shí)如此,您可以使用df.apply,給它一個(gè)計(jì)算特定行值的函數(shù):
def flag_value(row):
if row.entity == 10 and row.value != 1000 and row.location == CA:
return "A"
elif row.entity != 10 and row.entity != 0 and row.value == 1000 and row.location == US:
return "C"
elif row.entity == 0 and row.value == 1000 and row.location == US:
return "B"
else:
return "Different case"
df['flag'] = df.apply(flag_value, axis=1)
查看此相關(guān)問題以獲取更多信息。
如果您真的想查找指定某些條件的所有列,使用Pandas 數(shù)據(jù)框執(zhí)行此操作的常用方法是使用df.loc和索引:
only_a_cases = df.loc[df.entity == 10 & df.value != 1000 & df.location == "CA"]
# or:
only_a_cases = df.loc[lambda df: df.entity == 10 & df.value != 1000 & df.location == "CA"]
添加回答
舉報(bào)