Python 如何用函数(sin,line)填充pandas列?

Python 如何用函数(sin,line)填充pandas列?,python,pandas,numpy,dataframe,data-science,Python,Pandas,Numpy,Dataframe,Data Science,我有一个带有我自己添加的一些列的数据框架。有一个特定的列收集最大和最小潮位 问题是该列大部分为空,因为它只显示那些峰值,而不显示中间值。我想用一个类似于下图的函数来填充缺少的值 提前谢谢。因为您没有指定pandas数据帧使用的日期时间格式,下面是一个索引数据示例。如果它们间隔均匀且没有间隙,则可以使用它们 import pandas as pd import numpy as np from scipy.optimize import curve_fit tide = np.asarray

我有一个带有我自己添加的一些列的数据框架。有一个特定的列收集最大和最小潮位

问题是该列大部分为空,因为它只显示那些峰值,而不显示中间值。我想用一个类似于下图的函数来填充缺少的值


提前谢谢。

因为您没有指定pandas数据帧使用的日期时间格式,下面是一个索引数据示例。如果它们间隔均匀且没有间隙,则可以使用它们

import pandas as pd
import numpy as np
from scipy.optimize import curve_fit

tide = np.asarray([-1.2,np.nan,np.nan,3.4,np.nan,np.nan,-1.6,np.nan,np.nan,3.7,np.nan,np.nan,-1.4,])
tide_time = np.arange(len(tide))
df = pd.DataFrame({'a':tide_time,'b':tide}) 

#define your fit function with amplitude, frequence, phase and offset
def fit_func(x, ampl, freq, phase, offset):
    return ampl * np.sin(freq * x + phase) + offset

#extract rows that contain your values
df_nona = df.dropna()

#perform the least square fit, get the coefficients for your fitted data
coeff, _mat = curve_fit(fit_func, df_nona["a"], df_nona["b"])
print(coeff)

#append a column with fit data
df["fitted_b"] = fit_func(df["a"], *coeff)
我的示例数据的输出

#amplitude    frequency   phase       offset
[ 2.63098177  1.12805625 -2.17037976  1.0127173 ]

     a    b  fitted_b
0    0 -1.2 -1.159344
1    1  NaN -1.259341
2    2  NaN  1.238002
3    3  3.4  3.477807
4    4  NaN  2.899605
5    5  NaN  0.164376
6    6 -1.6 -1.601058
7    7  NaN -0.378513
8    8  NaN  2.434439
9    9  3.7  3.622127
10  10  NaN  1.826826
11  11  NaN -0.899136
12  12 -1.4 -1.439532

欢迎来到StackOverflow。请花点时间阅读这篇文章,以及如何提供答案,并相应地修改你的问题。这些提示可能也很有用。如果你想得到一个充分的答案,你应该更具体一点。可以使用自定义函数拟合数据,例如使用。但是这里的索引数据是什么@Piinthesky在其他人之间,我有一个datetime列,每15分钟登记一次日期。另一列(我感兴趣的那一列)是我前面解释的那一列。谢谢你的支持help@Piinthesky我不知道如何添加代码示例并查看输出
#amplitude    frequency   phase       offset
[ 2.63098177  1.12805625 -2.17037976  1.0127173 ]

     a    b  fitted_b
0    0 -1.2 -1.159344
1    1  NaN -1.259341
2    2  NaN  1.238002
3    3  3.4  3.477807
4    4  NaN  2.899605
5    5  NaN  0.164376
6    6 -1.6 -1.601058
7    7  NaN -0.378513
8    8  NaN  2.434439
9    9  3.7  3.622127
10  10  NaN  1.826826
11  11  NaN -0.899136
12  12 -1.4 -1.439532