我正在将大熊猫的分组结果写入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')
但是如何使它出现在结果之前的句子中?
答案 0 :(得分:2)
使用:
#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)