首页 > 解决方案 > 如何制作显示日期列范围的标题?

问题描述

我正在将 pandas 中分组的结果写入 txt。我想写一个句子来指代信息的范围。例子:

data for date 12/09/2018 to 16/09/2018

        dates   user  quantity
0        Sep  user_05    23
1        Sep  user_06    22
2        Sep  user_06    23     
3        Sep  user_07    22    
4        Sep  user_11    22
5        Sep  user_12    20
6        Sep  user_20    34
7        Sep  user_20    34

如果我这样做:

x['dates'].max()

给出:

  Timestamp('2018-09-16 00:00:00')

 x['dates'].min()

给出:

 Timestamp('2018-09-12 00:00:00')

但是我怎样才能让它出现在结果之前的一个句子中呢?

标签: pythonpandas

解决方案


利用:

#sample data
rng = pd.date_range('2017-04-03', periods=10)
x = pd.DataFrame({'dates': rng, 'a': range(10)})  
print (x)
       dates  a
0 2017-04-03  0
1 2017-04-04  1
2 2017-04-05  2
3 2017-04-06  3
4 2017-04-07  4
5 2017-04-08  5
6 2017-04-09  6
7 2017-04-10  7
8 2017-04-11  8
9 2017-04-12  9

#convert timestamps to strings
maxval = x['dates'].max().strftime('%d/%m/%Y')
minval = x['dates'].min().strftime('%d/%m/%Y')

#create sentence, 3.6+ solution
a = f'data for date {minval} to {maxval}'
#solution bellow 3.6
a = 'data for date {} to {}'.format(minval, maxval)
print (a)
data for date 03/04/2017 to 12/04/2017

#write sentence to file
df1 = pd.Series(a)
df1.to_csv('output.csv', index=False, header=None)
#append DataFrame to file
x.to_csv('output.csv', mode='a', index=False)

推荐阅读