python - 如何制作显示日期列范围的标题?
问题描述
我正在将 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')
但是我怎样才能让它出现在结果之前的一个句子中呢?
解决方案
利用:
#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)
推荐阅读
- c# - 为来宾用户显示 PowerBi 报告
- python - 如何使用 Python 阅读草稿邮件?
- python - Python CDLL 的 FileNotFoundError
- python - 将值分配给单个字符串python
- python-3.x - 为什么我必须在 Python 中两次导入一个库(IDLE 和导入的文件)?
- c# - C#如何创建具有多个相同键的字典?
- swift - 将我的结构重置为初始值或空值
- vue.js - 无法读取未定义的属性“requestContent”。电子版
- python - Python将输出打印到列表中
- php - 与 Laravel 中超过 2 个表的多对多关系