Python Pandas - 时间序列 - 00:00时缺失的时间戳
我正在尝试读取一个包含测量值的时间序列的csv文件。我的问题是,时间戳在从测量系统提取时,00:00的时间被省略了。
以下是csv文件的一部分:
Time NS Status u12 u23 u31 p1 q1
27.12.2023 23:30:00 0 0 20854,6 20482,8 20706,1 7599130 -2050710
27.12.2023 23:40:00 0 0 20882,8 20510,9 20728,6 7494070 -2078320
27.12.2023 23:50:00 0 0 20819,2 20448,5 20674,7 7672400 -1929610
28.12.2023 0 0 20792,9 20413,2 20645,9 7565910 -1942710
28.12.2023 00:10:00 0 0 20768,6 20368,6 20613,4 7174330 -2002890
我使用了:
df = pd.read_csv('C:/Python/Input/measured_values.csv',
sep = '\t', decimal=',',
skiprows=1, encoding='unicode_escape',
parse_dates=['Time'], dayfirst=True)
- 我尝试了parse_dates函数的不同参数来解决这个问题
- 我还尝试通过在时间序列的开始和结束之间递增时间来创建一个新的时间戳,但这并不简单,因为我需要注意时间的变化
有没有简单有效且稳健的方法来读取这种csv,并将时间列声明为datetime64[ns]?
2 个回答
-1
看起来你的问题是CSV文件在正好午夜的时候没有包含时间部分。
为了解决这个问题,你可以在读取CSV文件到数据框之前,先处理一下这个文件,确保所有的时间戳都有时间部分。
下面是你可以怎么做:
import pandas as pd
把CSV文件当作文本读取
with open('C:/Python/Input/measured_values.csv', 'r',
encoding='unicode_escape') as file:
lines = file.readlines()
处理每一行,确保所有的时间戳都有时间部分
processed_lines = []
for line in lines:
parts = line.split()
if len(parts) >= 3 and ':' not in parts[2]:
# If time component is missing, add it
parts.insert(2, '00:00:00')
processed_lines.append(' '.join(parts))
把处理过的内容写回一个临时文件
with open('temp.csv', 'w', encoding='unicode_escape') as file:
file.write('\n'.join(processed_lines))
把处理过的CSV文件读取到数据框中
df = pd.read_csv('temp.csv', sep='\t', decimal=',', skiprows=1,
parse_dates=['Time'], dayfirst=True)
可选的,你可以删除这个临时文件
import os
os.remove('temp.csv')
现在,df应该包含了带有正确时间部分的时间戳
print(df.head())
之后,使用pd.read_csv()把它读取到数据框中。这应该能解决你在午夜时缺少时间部分的问题。
1
你可以试着把 date_format='mixed'
这个参数传进去,并且可能需要去掉 skiprows=1
这个设置:
df = pd.read_csv(filename, sep='\t', decimal=',', encoding='unicode_escape',
parse_dates=['Time'], dayfirst=True, date_format='mixed')
print(df)
Time NS Status u12 u23 u31 p1 q1
0 2023-12-27 23:30:00 0 0 20854.6 20482.8 20706.1 7599130 -2050710
1 2023-12-27 23:40:00 0 0 20882.8 20510.9 20728.6 7494070 -2078320
2 2023-12-27 23:50:00 0 0 20819.2 20448.5 20674.7 7672400 -1929610
3 2023-12-28 00:00:00 0 0 20792.9 20413.2 20645.9 7565910 -1942710
4 2023-12-28 00:10:00 0 0 20768.6 20368.6 20613.4 7174330 -2002890
print(df.dtypes)
Time datetime64[ns]
NS int64
Status int64
u12 float64
u23 float64
u31 float64
p1 int64
q1 int64
dtype: object