Pandas根据不同的列插入NaN

Roj*_*ojj 7 python interpolation pandas

我有以下DataFrame(提取)

data = pd.DataFrame([[0., -10.88948939, 74.22099994, 1.5, "NW", 0], [0.819377018, -10.88948939, 74.22099994, 1.5, "NW", 1], [8.47965933, -10.88948939, 74.22099994, 1.5, "NW", 10], [15.38036833, -10.88948939, 74.22099994, 1.5, "NW", 20]], columns=["Velocity", "X", "Y", "Z", "wind_direction", "wind_speed"])

Velocity  X      Y     Z  wind_direction wind_speed
0        -10.88 74.22 1.5 NW             0
0.82     -10.89 74.22 1.5 NW             1
8.48     -10.89 74.22 1.5 NW             10
15.38    -10.89 74.22 1.5 NW             20
Run Code Online (Sandbox Code Playgroud)

它表示特定坐标(X,Y,Z)和两个边界条件(wind_direction和wind_speed)的CFD模拟结果.

我想估计相同点(X,Y,Z)的速度,相同的wind_direction,但是中间wind_speed,比如4.6.我的数据框中有这个额外的行

NaN -10.89 74.22 1.5 NW 4.6
Run Code Online (Sandbox Code Playgroud)

现在我想基于wind_speed进行插值以填充NaN.对于上面的例子,我希望得到6.643773541

数字来自线性插值:

0.82 +(4.6 - 1)/(10 - 1)*(8.48 - 0.82)

任何的想法?谢谢

UPDATE

我找到了上述问题的解决方案.诀窍是使用groupby并定义一个函数,该函数在groupby创建的数据帧上进行插值并传递给apply().就我而言,这就是功能

def interp(x, wind_speed):
    g = interpolate.interp1d(np.array(x["wind_speed"]), np.array(x["Velocity"]))
    return g(wind_speed)
Run Code Online (Sandbox Code Playgroud)

这是我的伙伴

group = df.groupby("point").apply(interp, wind_speed)
Run Code Online (Sandbox Code Playgroud)

必须使用表示执行插值的点的参数来调用函数interp.

我想知道是否有更好的方法来做到这一点.

umn*_*umn 7

我的解决方案是通过以下方式索引“wind_speed”:

df.set_index('wind_speed', inplace=True)
Run Code Online (Sandbox Code Playgroud)

然后我通过索引列进行插值

df.interpolate(method='index', inplace=True)
Run Code Online (Sandbox Code Playgroud)

现在我可以返回之前的状态

df.reset_index(inplace=True)
Run Code Online (Sandbox Code Playgroud)

让我知道是否进展顺利...


Roj*_*ojj 1

我已经找到了解决上述问题的方法。技巧是使用 groupby 并定义一个函数,该函数对由 groupby 创建并传递给 apply() 的数据帧进行插值。就我而言,这是函数

def interp(x, wind_speed):
    g = interpolate.interp1d(np.array(x["wind_speed"]), np.array(x["Velocity"]))
    return g(wind_speed)
Run Code Online (Sandbox Code Playgroud)

这是我的分组

group = df.groupby("point").apply(interp, wind_speed)
Run Code Online (Sandbox Code Playgroud)

必须使用表示执行插值点的参数来调用函数 interp。

我想知道是否有更好的方法来做到这一点。