填充NaN值

时间:2016-09-07 15:34:55

标签: python pandas missing-data

我有一个数据框

TIMESTAMP P_ACT_KW PERIODE_TARIF P_SOUSCR
2016-01-01 00:00:00 116 HC 250
2016-01-01 00:10:00 121 HC 250
2016-01-01 00:20:00 121 NaN 250

要使用此数据框,我必须根据以下条件填充NaN值(HC或HP):

If (hour extracted from TIMESTAMP is in {0,1,2, 3, 4, 5, 22, 23}

所以我用HC代替NaN, 否则由惠普。 我做了这个功能:

def prep_data(data):
    data['PERIODE_TARIF']=np.where(data['PERIODE_TARIF']in (0, 1,2, 3, 4, 5, 22, 23),'HC','HP')
    return data

但是我收到了这个错误:

 ValueError                                Traceback (most recent call last)
 <ipython-input-23-c1fb7e3d7b82> in <module>()
 ----> 1 prep_data(df_energy2)

 <ipython-input-22-04bd325f91cd> in prep_data(data)
       1 # Nettoyage des données
       2 def prep_data(data):
 ----> 3     data['PERIODE_TARIF']=np.where(data['PERIODE_TARIF']in (0, 1),'HC','HP')
       4     return data

 C:\Users\Demonstrator\Anaconda3\lib\site-packages\pandas\core\generic.py
 in __nonzero__(self)
     890         raise ValueError("The truth value of a {0} is ambiguous. "
     891                          "Use a.empty, a.bool(), a.item(), a.any() or a.all()."
 --> 892                          .format(self.__class__.__name__))
     893 
     894     __bool__ = __nonzero__

 ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

使用isin来测试会员资格:

data['PERIODE_TARIF']=np.where(data['PERIODE_TARIF'].isin([0, 1,2, 3, 4, 5, 22, 23]),'HC','HP')

in无法理解如何评估布尔值数组,因为如果数组中有多个True,它就会变得不明确,因此错误