Python 讀取.dat 文件的實現(xiàn)
寫在前面
使用matlab可以輸出為 .dat 或者 .mat 形式的文件,之前介紹過讀取 .mat 后綴文件,今天正好把 .dat 的讀取也記錄一下。
讀取方法
這里可以使用pandas庫將其作為一個dataframe的形式讀取進python,數(shù)據(jù)內容格式如下,根據(jù)空格分隔開分別為:
經(jīng)度、緯度、年、月、日、時、分、秒、變量數(shù)值
0 88.486 10.181 2023.0 3.0 20.0 0.0 15.0 0.0 3329.973 1 88.486 10.181 2023.0 3.0 20.0 0.0 30.0 0.0 3330.019 2 88.486 10.181 2023.0 3.0 20.0 0.0 45.0 0.0 3330.043 3 88.486 10.181 2023.0 3.0 20.0 1.0 0.0 0.0 3330.077
由于原始的dat文件中是沒有相關數(shù)據(jù)的信息的,這里為了方便后續(xù)處理,手動將其添加上相關的經(jīng)緯度信息
需要注意的是,在直接將 DataFrame 傳遞給 pd.DataFrame 構造函數(shù)并指定列名時,如果原始 DataFrame 的列數(shù)和新列名的數(shù)量不匹配,可能會導致數(shù)據(jù)不一致,從而生成 NaN 值。使用 to_numpy() 方法將 DataFrame 轉換為 NumPy 數(shù)組可以確保數(shù)據(jù)的一致性,因為它會忽略原始列名并僅保留數(shù)據(jù)。
- 讀取數(shù)據(jù)
import pandas as pd from datetime import datetime import numpy as np file_path = r'R:/ll/cj_YD_first_bpr_water_level.dat' df = pd.read_csv(file_path, header=None,sep=r'\s+') df
- 添加經(jīng)緯度信息
df_from_array = pd.DataFrame(df.to_numpy(), columns=['lon', 'lat', 'year', 'month', 'day', 'hour', 'min', 'sec', 'water'])
- 將時間提取出來作為新的一列,方便后續(xù)繪圖
df_from_array['datetime'] = df_from_array.apply(lambda row: datetime(year=int(row['year']), month=int(row['month']), day=int(row['day']), hour=int(row['hour']), minute=int(row['min']), second=int(row['sec'])),axis=1) df_from_array
這里,做一個特殊的預處理,由于需要時刻的數(shù)據(jù)是相同的經(jīng)緯度位置的,這里挑選出所有相同經(jīng)緯度坐標點的數(shù)據(jù)
grouped = df_from_array.groupby(['lon', 'lat','datetime'])['water'].apply(list).reset_index() grouped
- 發(fā)現(xiàn)存在缺測的站點,剔除掉缺測的經(jīng)緯度數(shù)據(jù)
grouped = grouped[(grouped['lon'] != -9999.0000) & (grouped['lat'] != -9999.0000)] grouped['water'] = grouped['water'].apply(lambda x: x[0]) grouped
繪圖
挑選相同站點,不同時間的數(shù)據(jù)繪制曲線,為了避免不同位置的站點的數(shù)據(jù)大小存在較大差異,設置不同的y軸來表征
fig, ax1 = plt.subplots(figsize=(15, 10), dpi=200) plt.rcParams['axes.unicode_minus'] = False plt.rcParams['font.sans-serif'] = ['Times New Roman'] plt.rcParams['font.size'] = 16 axes = [ax1] colors = plt.cm.tab10.colors lines = [] labels = [] for i, (_, coord) in enumerate(unique_coords.iterrows()): lon = coord['lon'] lat = coord['lat'] filtered_data = grouped[(grouped['lon'] == lon) & (grouped['lat'] == lat)] if i == 0: ax = ax1 else: ax = ax1.twinx() axes.append(ax) ax.spines['right'].set_position(('outward', 80 * (i - 1))) color = colors[i % len(colors)] line, = ax.plot(filtered_data['datetime'], filtered_data['water'], color=color, linewidth=0.9, linestyle='-', label=f'Lon: {lon}, Lat: {lat}') ax.set_ylabel(f' (Lon: {lon}, Lat: {lat})') ax.yaxis.label.set_color(color) ax.tick_params(axis='y', colors=color) lines.append(line) labels.append(f'Lon: {lon}, Lat: {lat}') ax1.legend(lines, labels, loc='best',ncols=2, bbox_to_anchor=(0.9, 1)) plt.xticks(rotation=55) plt.grid() fig.suptitle('Data Over Time for Different station', y=0.95) plt.tight_layout() plt.show()
總結
復習了一下使用pandas讀取.dat文件的相關函數(shù),以及pandas的一些基礎命令,繪圖多y軸的方法。相關數(shù)據(jù)和代碼放到GitHub上
到此這篇關于詳解用python實現(xiàn)爬取CSDN熱門評論URL并存入redis的文章就介紹到這了,更多相關python爬取URL內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
Python判斷一個list中是否包含另一個list全部元素的方法分析
這篇文章主要介紹了Python判斷一個list中是否包含另一個list全部元素的方法,結合實例形式對比分析了Python針對列表list元素包含關系的相關轉換、判斷操作技巧,需要的朋友可以參考下2018-12-12Python深度學習實戰(zhàn)PyQt5窗口切換的堆疊布局示例詳解
本文以堆疊窗口控件為例,詳細介紹堆疊布局的界面設計和程序實現(xiàn)過程,通過案例帶小白創(chuàng)建一個典型的堆疊布局多窗口切換程序2021-10-10Python爬取智聯(lián)招聘數(shù)據(jù)分析師崗位相關信息的方法
這篇文章主要介紹了Python爬取智聯(lián)招聘數(shù)據(jù)分析師崗位相關信息的方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧2019-08-08Python cookbook(數(shù)據(jù)結構與算法)通過公共鍵對字典列表排序算法示例
這篇文章主要介紹了Python cookbook(數(shù)據(jù)結構與算法)通過公共鍵對字典列表排序算法,結合實例形式分析了Python基于operator模塊中的itemgetter()函數(shù)對字典進行排序的相關操作技巧,需要的朋友可以參考下2018-03-03