alter for循环跳过缺少值的记录

时间:2018-03-15 00:50:27

标签: python-2.7 pandas

当我运行下面的代码时,我收到以下错误。似乎正在发生的事情是,对于我的good_df数据框中的某些_place记录,没有带有stf_id的hcat和goodsellers字段中没有条目。 goodsellers字段具有由管道分隔的串联值。因为它不能在管道上拆分,因为没有任何值,它会在遇到丢失的记录时抛出错误。

我宁愿修改代码,以便它只是跳到下一个_place记录,有人可以建议怎么做吗?

Code:

stf_id = good_df['hcat'].unique()
place = good_df['_place'].unique()

for stf_id in stf_id:
    for place in place:
        print("%s | %s" % (place, stf_id))
        goodsellers = good_df[(good_df['hcat']==stf_id) & (good_df['_place']==place)]['goodsellers'].squeeze().split("|")

        display_th_pan(goodsellers[:10], ds)


Error:

AttributeErrorTraceback (most recent call last)
<ipython-input-8-5656b6495fa9> in <module>()
      2     for place in place:
      3         print("%s | %s" % (place, stf_id))
----> 4         goodsellers = good_df[(good_df['hcat']==stf_id) & (good_df['_place']==place)]['goodsellers'].squeeze().split("|")
      5 
      6         display_th_pan(goodsellers[:10], ds)

/data2/453/anaconda2/lib/python2.7/site-packages/pandas/core/generic.pyc in __getattr__(self, name)
   3612             if name in self._info_axis:
   3613                 return self[name]
-> 3614             return object.__getattribute__(self, name)
   3615 
   3616     def __setattr__(self, name, value):

AttributeError: 'Series' object has no attribute 'split'

1 个答案:

答案 0 :(得分:1)

for stf_id in stf_id:
    for place in place:
        print("%s | %s" % (place, stf_id))    
        try:
            goodsellers = good_df[(good_df['hcat']==stf_id) & (good_df['_place']==place)]['goodsellers'].squeeze().split("|")
        except AttributeError:
            print("skipped to the next _place record")
            continue
        display_th_pan(goodsellers[:10], ds)