作者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/cn.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