通过字符串的开头过滤dataframe列

时间:2017-05-16 00:30:19

标签: python-3.x pandas

我想按字符串的开头19个字符(符合要求)过滤以下数据框行。

截至目前,数据框架如下所示:

        Name    Reason
   0    item1   {"state": "doesn't meet requirements" , "score": "0.6"}
   1    item2   {"state": "meets requirements" , "score": "0.7"}
   2    item3   {"state": "meets requirements" , "score": "0.8"}
   3    item4   {"state": "doesn't requirements" , "score": "0.9"}
   4    item5   {"state": "meets requirements" , "score": "0.7"}
   5    item6   {"state": "doesn't requirements" , "score": "0.7"}

我期待的结果是数据框看起来像这样:

    Name    Reason
0   item2   {"state": "meets requirements" , "score": "0.7"}
1   item3   {"state": "meets requirements" , "score": "0.8"}
2   item5   {"state": "meets requirements" , "score": "0.7"}

基本上是过滤,以便剩下的唯一行是那些乞求"满足要求"在" Reason"专栏

由于

1 个答案:

答案 0 :(得分:1)

#strip the spaces and compare with the prefix and then filter the rows 
df[df.Reason.str.replace(' ','').str.startswith('{"state":"meetsrequirements"')]
Out[236]: 
     Name                                            Reason
1   item2  {"state": "meets requirements" , "score": "0.7"}
2   item3  {"state": "meets requirements" , "score": "0.8"}
4   item5  {"state": "meets requirements" , "score": "0.7"}