作者world4849844 (倪好嗎)
看板Python
標題[問題] if判斷式遇到ValueError
時間Mon Mar 30 19:06:59 2020
想從一個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://webptt.com/m.aspx?n=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
1F:推 cuteSquirrel: 試試看 isin 語法 03/30 19:22
4F:推 yuasa: 我從沒用過pandas處理中文字。但我記得Pandas contains只 03/30 19:42
5F:→ yuasa: 能找"在字串中間"的。假如你的location是 '在台北市地區', 03/30 19:43
6F:→ yuasa: contains就找的到。你這個直接用loc就可以了吧? 03/30 19:43
7F:→ yuasa: 你也可以試試startswith代替contains 03/30 19:45
8F:推 pmove: 我也沒用過pandas,但是contain裡面的 台北市,為何不是字串 03/30 19:54
9F:→ pmove: ?(沒有‘) 03/30 19:54
10F:→ world4849844: 感謝各位大大提供的資訊,先回應樓上的大大,我忘記 03/30 20:11
11F:→ world4849844: 打到' ',contains中是('台北市')是這樣才對,conta 03/30 20:11
12F:→ world4849844: ins單獨拉出來確實能得到資料,但是前面的if的判斷 03/30 20:11
13F:→ world4849844: 式中沒辦法將各個城市的名稱用in [list]的方式或'城 03/30 20:11
14F:→ world4849844: 市名稱'or '城市名稱'分類 03/30 20:11
15F:→ world4849844: 感謝各位大大解惑,是我自己將append()內加入兩筆資 03/30 21:58
16F:→ world4849844: 料,才會有錯誤,已經改正了 03/30 21:59
17F:推 cayut: 用樓上那個isin搭配any就可以放在if了 03/31 01:38
18F:→ cayut: if df.location.isin(['台北市']).any(): 03/31 01:40