[問題] if判斷式遇到ValueError

看板Python作者 (倪好嗎)時間5年前 (2020/03/30 19:07), 5年前編輯推噓5(5013)
留言18則, 5人參與, 5年前最新討論串1/1
想從一個dataframe中取得某些特定關鍵字的資料 year location rainfall 01 107 台北市 90 02 107 新北市 80 03 108 台北市 70 類似上面的dataframe取得北部區域的資料 附上程式碼 if location in ['台北市', '新北市', '基隆市']: a = df[df.location.str.contain(台北市)] b = df[df.location.str.contain(新北市)] c = df[df.location.str.contain(基隆市)] d = a.append(b,c) return d elif 其他區域 跑的時候遇到 ValueError:The truth value of a DataFrame is ambitious. 有嘗試將 if location in ['台北市', '新北市', '基隆市'] 改成 if location == '台北市' or '新北市' or '基隆市' 或用 | 連結都錯誤 有沒有大大知道如何整理此類的資料,或者有資料整理的資源,感謝各位大大 -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 27.52.37.172 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/Python/M.1585566421.A.52E.html ※ 編輯: world4849844 (27.52.37.172 臺灣), 03/30/2020 19:09:08 ※ 編輯: world4849844 (27.52.37.172 臺灣), 03/30/2020 19:10:40

03/30 19:22, 5年前 , 1F
試試看 isin 語法
03/30 19:22, 1F

03/30 19:23, 5年前 , 2F
03/30 19:23, 2F

03/30 19:25, 5年前 , 3F
官網isin介紹: https://bit.ly/3dDdRaw
03/30 19:25, 3F

03/30 19:42, 5年前 , 4F
我從沒用過pandas處理中文字。但我記得Pandas contains只
03/30 19:42, 4F

03/30 19:43, 5年前 , 5F
能找"在字串中間"的。假如你的location是 '在台北市地區',
03/30 19:43, 5F

03/30 19:43, 5年前 , 6F
contains就找的到。你這個直接用loc就可以了吧?
03/30 19:43, 6F

03/30 19:45, 5年前 , 7F
你也可以試試startswith代替contains
03/30 19:45, 7F

03/30 19:54, 5年前 , 8F
我也沒用過pandas,但是contain裡面的 台北市,為何不是字串
03/30 19:54, 8F

03/30 19:54, 5年前 , 9F
?(沒有‘)
03/30 19:54, 9F

03/30 20:11, 5年前 , 10F
感謝各位大大提供的資訊,先回應樓上的大大,我忘記
03/30 20:11, 10F

03/30 20:11, 5年前 , 11F
打到' ',contains中是('台北市')是這樣才對,conta
03/30 20:11, 11F

03/30 20:11, 5年前 , 12F
ins單獨拉出來確實能得到資料,但是前面的if的判斷
03/30 20:11, 12F

03/30 20:11, 5年前 , 13F
式中沒辦法將各個城市的名稱用in [list]的方式或'城
03/30 20:11, 13F

03/30 20:11, 5年前 , 14F
市名稱'or '城市名稱'分類
03/30 20:11, 14F

03/30 21:58, 5年前 , 15F
感謝各位大大解惑,是我自己將append()內加入兩筆資
03/30 21:58, 15F

03/30 21:59, 5年前 , 16F
料,才會有錯誤,已經改正了
03/30 21:59, 16F

03/31 01:38, 5年前 , 17F
用樓上那個isin搭配any就可以放在if了
03/31 01:38, 17F

03/31 01:40, 5年前 , 18F
if df.location.isin(['台北市']).any():
03/31 01:40, 18F
文章代碼(AID): #1UWTBLKk (Python)
文章代碼(AID): #1UWTBLKk (Python)