如何用Python将多行字符串格式的时序温度数据转换为结构化表格
实现代码
以下提供两种实现方案,可根据使用场景选择:
纯Python实现(无第三方依赖)
不需要安装额外库,直接运行即可生成结构化结果,支持导出为CSV格式:
def time_str_to_sec(time_str): # 将"时:分:秒.毫秒"格式的字符串转换为总秒数 h, m, s = time_str.split(':') return float(h) * 3600 + float(m) * 60 + float(s) # 实际使用时可替换为从文件读取:with open('你的数据文件路径.txt') as f: raw_data = f.readlines() raw_data = [ "19:27:39.829 -> 23.06,23.31", "19:27:41.273 -> 23.06,23.31", "19:27:42.717 -> 23.06,23.31" ] result = [] base_time = None for line in raw_data: # 自动跳过空行 if not line.strip(): continue # 拆分时间部分和温度部分 time_part, temp_part = line.strip().split('->') current_sec = time_str_to_sec(time_part.strip()) # 取首行时间作为计算相对时间的基准 if base_time is None: base_time = current_sec # 计算相对时间,保留三位小数 relative_time = round(current_sec - base_time, 3) # 拆分两个温度值 temp1, temp2 = temp_part.strip().split(',') result.append([relative_time, float(temp1), float(temp2)]) # 打印表格结果 print(f"{'Time Value':<12} {'Temperature One':<16} {'Temperature Two':<16}") print("-"*44) for row in result: print(f"{row[0]:<12.3f} {row[1]:<16.2f} {row[2]:<16.2f}") # 如需导出为CSV文件,取消注释以下代码即可 # import csv # with open('output.csv', 'w', newline='') as f: # writer = csv.writer(f) # writer.writerow(['Time Value', 'Temperature One', 'Temperature Two']) # writer.writerows(result)
Pandas实现(直接生成结构化表格)
如果已经安装Pandas库,可直接生成DataFrame格式的结构化表格,方便后续数据处理、分析:
import pandas as pd def time_str_to_sec(time_str): h, m, s = time_str.split(':') return float(h) * 3600 + float(m) * 60 + float(s) # 实际使用时可替换为从文件读取:raw_data = pd.read_csv('你的数据文件路径.txt', sep='->', header=None, names=['time_str', 'temp_str'], engine='python') raw_data = pd.DataFrame([ "19:27:39.829 -> 23.06,23.31", "19:27:41.273 -> 23.06,23.31", "19:27:42.717 -> 23.06,23.31" ], columns=['raw']) # 拆分原始数据 raw_data[['time_str', 'temp_str']] = raw_data['raw'].str.split('->', expand=True) raw_data['time_str'] = raw_data['time_str'].str.strip() raw_data['temp_str'] = raw_data['temp_str'].str.strip() # 计算相对时间 raw_data['total_sec'] = raw_data['time_str'].apply(time_str_to_sec) base_sec = raw_data['total_sec'].iloc[0] raw_data['Time Value'] = (raw_data['total_sec'] - base_sec).round(3) # 拆分温度列 raw_data[['Temperature One', 'Temperature Two']] = raw_data['temp_str'].str.split(',', expand=True).astype(float) # 提取最终结构化表格 result_df = raw_data[['Time Value', 'Temperature One', 'Temperature Two']] print(result_df) # 导出为CSV文件:result_df.to_csv('output.csv', index=False)
运行结果示例
两种方案的输出结果一致:
Time Value Temperature One Temperature Two 0.000 23.06 23.31 1.444 23.06 23.31 2.888 23.06 23.31
内容的提问来源于stack exchange,提问作者Aradhya Jain
相关产品推荐
相关产品推荐

