-
需要从文件中读取数据,文件格式如下:
CIRCUITNAME=CIRCUIT1 00.12 12/20 2.3 23.6 00.12 12/20 2.3 23.6 00.42 12/20 2.2 23.3 00.42 12/20 2.2 23.3 00.42 12/20 2.2 23.3 01.12 12/20 2.2 23.1 01.12 12/20 2.2 23.1 -
需要编写一个函数来读取文件,并返回每个列对应的numpy数组。
-
问题在于无法将月份和日期保存为浮点数,因为它们之间有“/”。
-
需要将月份和日期保存为“12.05”的格式,其中“12.05”表示5月12日。
-
当进入下一天时,“12.05”变为“12.06”,并且需要相应地保存时间值,方法是为新的一天添加小时。
- 解决方案
-
使用
datetime模块来解析日期和时间。 -
使用
strftime()方法将日期和时间格式化为“%m.%d”的格式。 -
使用
astype(float)方法将格式化的日期和时间转换为浮点数。 -
使用
timedelta对象来表示时间差。 -
使用
add()方法将时间差添加到日期和时间。
import numpy as np
import datetime
def load_ci(filepath):
fileObj = open(filepath, 'r')
time_1 = []
time_2 = []
date_count = []
t = 0
ti = 0
d = ""
# da=0
loadCurrent_1 = []
surfaceTemp_1 = []
loadCurrent_2 = []
surfaceTemp_2 = []
ambient = []
read = 0
for line in fileObj:
if not line.strip():
continue
if read == 1:
if '[AMBIENT]' in line:
read = 3
continue
elif 'CIRCUITNAME=CIRCUIT2' in line:
read = 2
else:
if line != '\n' and '[CIRCUIT2]' not in line:
point = line.split(' ')
date_count.append(point[1])
t = (float(point[0]))
ti = int(t) * 3600 + (t - int(t)) * 60 * 100
time_1.append(ti)
loadCurrent_1.append(float(point[2]))
surfaceTemp_1.append(float(point[3]))
if read == 2:
if '[AMBIENT]' in line:
read = 3
continue
elif 'CIRCUITNAME=CIRCUIT2' in line:
read = 2
else:
if line != '\n' and '[CIRCUIT2]' not in line:
point = line.split(' ')
t = (float(point[0]))
ti = int(t) * 3600 + (t - int(t)) * 60 * 100
time_2.append(ti)
loadCurrent_2.append(float(point[2]))
surfaceTemp_2.append(float(point[3]))
if read == 3:
if line != '\n':
point = line.split(' ')
ambient.append(float(point[2]))
if 'CIRCUITNAME=CIRCUIT1' in line:
read = 1
return np.array(loadCurrent_1), np.array(surfaceTemp_1), np.array(loadCurrent_2), np.array(
surfaceTemp_2), np.array(ambient), np.array(time_1), np.array(time_2), np.array(date_count)
def convert_date_to_float(date_str):
"""
Convert a date string in the format "mm/dd" to a float.
Args:
date_str: The date string to convert.
Returns:
A float representing the date.
"""
date = datetime.datetime.strptime(date_str, "%m/%d")
return float(date.strftime("%m.%d"))
def add_time_to_date(date_float, time_seconds):
"""
Add a time difference to a date.
Args:
date_float: The date as a float.
time_seconds: The time difference in seconds.
Returns:
A new date float with the time difference added.
"""
date = datetime.datetime.strptime(str(date_float), "%m.%d")
time_delta = datetime.timedelta(seconds=time_seconds)
new_date = date + time_delta
return float(new_date.strftime("%m.%d"))
# Load the data from the file
a = load_ci("2_Horizontal_Drilling_800mm_20121221_001235.ci")
# Convert the date strings to floats
date_floats = np.array([convert_date_to_float(date) for date in a[7]])
# Add the time values to the dates
new_date_floats = np.array([add_time_to_date(date, time) for date, time in zip(date_floats, a[5])])
# Print the new date floats
print(new_date_floats)