Python通过插值引用数据

2024-06-02 05:41:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有两个数据集,其中一个有时间数组日期时间。日期时间和x,y,z坐标的时间数组,像time[0]=datetime.datetime(2000,1,21,0,7,25), x[0]=-6.7, etc.

我想从坐标计算一些东西,但这需要另一个依赖于时间的参数(Ma)。第二个数据集有另一个相同datetime格式的时间数组,参数记录在该时间,如time[0]=datetime.datetime(2000,1,1,0,3), Ma[0]=2.73

问题是两个数据集的时间数组不同(尽管范围相似)

所以我想在数据集1的每个时间内插参数的值,比如Ma[0],但是0不是数据集2的时间索引,而是对应于数据集1的索引。 我该怎么做?你知道吗

另外,我能把时间形式转换成更简单的形式吗?日期时间。日期时间看起来很麻烦。你知道吗


Tags: 数据参数datetimetime格式记录时间etc
1条回答
网友
1楼 · 发布于 2024-06-02 05:41:12

下面是一个如何插值的例子。coord_ma_数组将是导入的数据。你知道吗

脚本要做的第一件事是从不同的一维数组中构建一些更合理的数据结构。您实际要查找的部分是对np.interpdocumented here的调用。你知道吗

import numpy as np
import datetime
import time

# Numpy cannot interpolate between datetimes
# This function converts a datetime to a timestamp
def to_ts(dt):
    return time.mktime(dt.timetuple())

coord_dts = np.array([
    datetime.datetime(2000, 1, 1, 12),
    datetime.datetime(2000, 1, 2, 12),
    datetime.datetime(2000, 1, 3, 12),
    datetime.datetime(2000, 1, 4, 12)
])

coord_xs = np.array([3, 5, 8, 13])
coord_ys = np.array([2, 3, 5, 7])
coord_zs = np.array([1, 3, 6, 10])

ma_dts = np.array([
    datetime.datetime(2000, 1, 1),
    datetime.datetime(2000, 1, 2),
    datetime.datetime(2000, 1, 3),
    datetime.datetime(2000, 1, 4)
])

ma_vals = np.array([1, 2, 3, 4])

# Handling the data as separate arrays will be painful.
# This builds an array of dictionaries with the form:
#   [ { 'time': timestamp, 'x': x coordinate, 'y': y coordinate, 'z': z coordinate }, ... ]
coords = np.array([
    { 'time': to_ts(coord_dts[idx]), 'x': coord_xs[idx], 'y': coord_ys[idx], 'z': coord_zs[idx] }
    for idx, _ in enumerate(coord_dts)
])

# Build array of timestamps from ma datetimes
ma_ts = [ to_ts(dt) for dt in ma_dts ]

for coord in coords:
    print("ma interpolated value", np.interp(coord['time'], ma_ts, ma_vals))
    print("at coordinates:", coord['x'], coord['y'], coord['z'])

相关问题 更多 >