python处理txt数据写入columns和index

一、parsivel雨滴谱数据:

二、数据介绍:

 总结一下就是,第一行数据是第一个速度对应的全部32个尺度粒子个数,第二行数据是第二个速度对应的全部32个尺度粒子个数。

 三、速度、尺度一览表:

四、先将速度、尺度数据放入原雨滴谱txt数据中,以方便后期计算:

(1)先按时间进行分组

(2)再按行读取,将每个部分变成列表,放入dataframe里

(3)最后插入雨滴谱速度尺度文件

#!usr/bin/env python
# -*- coding:utf-8 -*-
"""
@author: Suyue
@file: speedeeinsert.py
@time: 2024/04/07
@desc:
"""
import numpy as np
import pandas as pd
df1 = pd.read_excel('G:/尺度速度.xls')

file_path = 'G:/NM004-20230627224400-20230627224859-0.txt'

# 读整个txt文件读取到单个字符串
with open(file_path, 'r', errors='ignore') as file:
    file_content = file.read()

# 按时间戳拆分内容以查找单独的部分
# 时间戳的格式为 YYYY-MM-DD HH:MM:SS,因此我们将使用正则表达式根据此模式进行拆分
import re
sections = re.split(r'\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\n', file_content)
# print(sections)

# 如果txt第一个元素为空值(由于拆分),则将其删除
if not sections[0]:
    sections.pop(0)

# 将每个部分放入列表
list = []
for section in sections[1:]:
    # 将字符串拆分为几行,然后按空格拆分每行并转换为 DataFrame
    lines = section.strip().split('\n')
    # print(lines)
    matrix = [line.split() for line in lines]
    df = pd.DataFrame(matrix)
    # print(matrix)

    df.columns = df1['直径']
    df.index = df1['速度']
    
    # 将df放入list中
    list.append(df)
    # print(list)
    # 将结果存入excel
    rdf = pd.concat(list,axis=0)
    rdf.to_excel('G:/NM004-20230627224400-20230627224859-0.xlsx')


# 显示每个dataframe形状以确认
df_shapes = [df.shape for df in list]
print(df_shapes)

 结果:

 

posted @ 2024-04-08 09:21  秋刀鱼CCC  Views(114)  Comments(0Edit  收藏  举报