You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将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_datesentry_count
02003-01-021
12015-10-311
22015-11-0114
32015-11-0217
42015-11-0311
52015-11-043

方法二:基于你已有的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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:12:32