我试图根据日期列对(ascending)进行排序,并想检查第一行是否在日期范围内。因此,我可以确保不适合该过程的特定文件。
eg: file A : contains July+August records
file B : contains September+October records
我只想选择file B
。如果按日期排序,fileA的第一条记录将是7月record/August记录。
排序后,我应该如何选择第一条记录?
start, end = get_previous_month_start_end()
df.sort_values('Document Date') <--pick first record from ascending order
if not df[df['Document Date'].between(start, end)]
print ('This is not in the date range')
分析解答
使用Series.sort_values
并通过Series.iat
或Series.nsmallest
选择第一个值-它返回一个元素系列,因此也需要通过iat
选择:
np.random.seed(2019)
rng = pd.date_range('2017-04-03', periods=10)
df = pd.DataFrame({'Document Date': rng, 'a':np.random.randint(10, size=10)}).sort_values('a')
print (df)
Document Date a
6 2017-04-09 0
7 2017-04-10 0
1 2017-04-04 2
2 2017-04-05 5
4 2017-04-07 6
8 2017-04-11 7
0 2017-04-03 8
3 2017-04-06 8
5 2017-04-08 8
9 2017-04-12 8
a = df['Document Date'].sort_values().iat[0]
print(a)
2017-04-03 00:00:00
a = df['Document Date'].nsmallest(1).iat[0]
print (a)
2017-04-03 00:00:00