在Pandas中有条件地将整行设置为NaN/None

the*_*tro 3 python dataframe pandas

我有一个按日期索引的DataFrame.我希望能够将索引大于某个值的所有行(如今)取出,但将它们保存在DataFrame中.最好的方法是什么?比如这个

10/20/16  15, 20
10/25/16  13, 12
10/30/16  16, 15

#--> 10/30/16 should go to NaN, NaN
Run Code Online (Sandbox Code Playgroud)

piR*_*red 5

df.loc[df.index > pd.datetime.today()] = np.nan
df
Run Code Online (Sandbox Code Playgroud)

在此处输入图片说明


jez*_*ael 5

与解决方案DataFrame.mask,对于mask需要相同indexdf:

#convert index to datetime
df.index = pd.to_datetime(df.index)

mask = pd.Series(df.index > pd.datetime.today(), index=df.index)
print (mask)
Date
2016-10-20    False
2016-10-25    False
2016-10-30     True
dtype: bool

df = df.mask(mask)
print (df)
               a     b
Date                  
2016-10-20  15.0  20.0
2016-10-25  13.0  12.0
2016-10-30   NaN   NaN
Run Code Online (Sandbox Code Playgroud)