[英]Python Pandas - using .loc to select with AND and OR on multiple columns
[英]Python :How to use loc with multiple columns in pandas
我有一個包含多列的 df。 我們需要檢查是否有任何列的值為 0; 如果有 0,我們必須添加帶有標簽的新列。
我試過這個:
df.loc[df['maths'] == '0', 'mark_student'] = 'fail'
這適用於單列,但是當我嘗試多列時,它失敗了
像這樣:
df.loc[df['maths','chemistry'] == '0', 'mark_student'] = 'fail'
df.loc[df[['maths','chemistry']] == '0', 'mark_student'] = 'fail'
df[['maths','chemistry']] == '0'
返回一個數據幀,不能直接用作行級的 boolean 索引。 您可以使用.any(1)
將其縮減為系列,然后將其與.loc
一起使用:
df.loc[(df[['maths','chemistry']] == '0').any(1), 'mark_student'] = 'fail'
應該管用。
您必須使用 () 每個條件, df.loc[(df['maths'] == 0) & (df['chemistry'] == 0) & (df['mark_student'] == 'fail')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.