我尝试在 fillna 中使用 math.sin() 函数,但失败了:
data['Sensor #1'].fillna(math.sin(data["Sample #"] * parameter), inplace = True)
有什么办法可以解决这个问题吗?
错误消息如下:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-145-9199336c2860> in <module>()
11
12
---> 13 data['Sensor #1'].fillna(math.sin(data["Sample #"] * parameter), inplace = True)
14 data['Sensor #2'].fillna(lambda r: r["Sample #"]**-parameter, inplace = True)
15 # drop the row that has empty value(s) because we want to find anomalies
/anaconda3/lib/python3.6/site-packages/pandas/core/series.py in wrapper(self)
115 return converter(self.iloc[0])
116 raise TypeError("cannot convert the series to "
--> 117 "{0}".format(str(converter)))
118
119 return wrapper
TypeError: cannot convert the series to <class 'float'>
最佳答案
您正在使用需要标量输入的函数。 math.sin
期望单个值,即:
>>> math.sin(1)
0.8414709848078965
您需要一个向量化函数来查找系列中每个值的正弦,在本例中由 numpy
库提供:
>>> s = pd.Series([1,2,3])
>>> np.sin(s)
0 0.841471
1 0.909297
2 0.141120
dtype: float64
<小时/>
如果您没有安装numpy
,您有两个选择:
- 运行
pip install numpy
- 改用
pd.np.sin
其余代码看起来不错,这是一个工作示例:
df = pd.DataFrame({'a': [1,2,3], 'b': [4,5,6], 'c': [np.nan, 0.84, np.nan]})
a b c
0 1 4 NaN
1 2 5 0.84
2 3 6 NaN
df.assign(c=df.c.fillna(np.sin(df.a)*df.b))
a b c
0 1 4 3.365884
1 2 5 0.840000
2 3 6 0.846720
关于python - 如何在 pandas 的 fillna 中使用 math.sin(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52450011/