如何将DataFrame日期统计结果转换为新的DataFrame?
解决方法:将计数结果转为带表头的DataFrame
你已经离目标很近啦!其实df2['just_dates'].value_counts().sort_index()返回的本身是一个pandas Series,你把它放进列表里反而多了一步,直接把这个Series转成DataFrame就行,还能自定义表头。
方法一:直接转换(推荐)
先获取排序后的计数值Series,再用reset_index()把它转成DataFrame,同时指定列名:
# 获取按日期排序的计数Series count_series = df2['just_dates'].value_counts().sort_index() # 转成DataFrame,指定索引列和计数列的名称 count_df = count_series.reset_index(names='just_dates', name='entry_count')
执行后,count_df就是你想要的结构:
| just_dates | entry_count | |
|---|---|---|
| 0 | 2003-01-02 | 1 |
| 1 | 2015-10-31 | 1 |
| 2 | 2015-11-01 | 14 |
| 3 | 2015-11-02 | 17 |
| 4 | 2015-11-03 | 11 |
| 5 | 2015-11-04 | 3 |
方法二:基于你已有的out列表转换
如果你已经把结果放进了out列表,直接取列表里的第一个元素(也就是那个Series)来转换就行:
# 从out列表中取出Series并转成DataFrame count_df = out[0].reset_index(names='just_dates', name='entry_count')
关键说明
reset_index()的作用是把原来的日期索引(Series的索引)转换成DataFrame的普通列,同时生成默认的行号索引。names参数用来给原来的索引列(日期列)命名,name参数用来给计数列命名,你可以根据需求改成自己喜欢的名字,比如把entry_count改成total_items。
内容的提问来源于stack exchange,提问作者Dennis
相关产品推荐
相关产品推荐

