1

我尝试在 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'>
4

1 回答 1

2

您正在使用一个需要标量输入的函数。 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
于 2018-09-21T19:37:45.097 回答