3
我有一個按日期索引的DataFrame。我希望能夠清空索引大於某個值的所有行(如今天),但將它們保留在DataFrame中。什麼是最好的方法來做到這一點?例如,這有條件地將整個行設置爲NaN /無在熊貓中
10/20/16 15, 20
10/25/16 13, 12
10/30/16 16, 15
#--> 10/30/16 should go to NaN, NaN
我有一個按日期索引的DataFrame。我希望能夠清空索引大於某個值的所有行(如今天),但將它們保留在DataFrame中。什麼是最好的方法來做到這一點?例如,這有條件地將整個行設置爲NaN /無在熊貓中
10/20/16 15, 20
10/25/16 13, 12
10/30/16 16, 15
#--> 10/30/16 should go to NaN, NaN
解決方案與DataFrame.mask
,爲mask
需要同index
爲df
:
#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