使用Pandas.DataFrame.from_dict时如何将UNIX时间戳转换为日期时间?
使用Pandas.DataFrame.from_dict时如何将UNIX时间戳转换为日期时间?
当然可以用Pandas.DataFrame.from_dict来处理你的需求!这里有两种便捷的方案,你可以根据自己的偏好选择:
方案一:生成DataFrame后转换索引
这种方法不需要修改原始字典,直接在DataFrame层面处理索引,步骤很简单:
import pandas as pd import json with open('data.json', 'r') as json_file: data_pairs = json.load(json_file) # 先用from_dict生成DataFrame,指定orient='index',同时给列命名(可选,让数据更清晰) df = pd.DataFrame.from_dict(data_pairs, orient='index', columns=['count']) # 将字符串类型的毫秒级时间戳索引转换为datetime df.index = pd.to_datetime(df.index, unit='ms')
注意:你的时间戳是毫秒级的(比如1707195600000对应2024年2月),所以一定要加上unit='ms'参数,否则Pandas会把它当作秒级时间戳解析,得到错误的日期。
方案二:先转换字典键再生成DataFrame
如果你希望先处理好字典再生成DataFrame,也可以提前把键转成datetime对象:
import pandas as pd import json with open('data.json', 'r') as json_file: data_pairs = json.load(json_file) # 遍历字典,将每个字符串时间戳转为datetime,值保持不变 converted_data = {pd.to_datetime(timestamp, unit='ms'): value for timestamp, value in data_pairs.items()} # 用转换后的字典生成DataFrame df = pd.DataFrame.from_dict(converted_data, orient='index', columns=['count'])
这种方式适合后续还要用到转换后字典的场景,而且pd.to_datetime可以直接处理字符串类型的时间戳,不需要额外转成整数。
两种方案都能完美实现你的需求,选哪种全看你的工作流程偏好~
备注:内容来源于stack exchange,提问作者binary_assemble
相关产品推荐
相关产品推荐

