python - 如何在 pandas 的 fillna 中使用 math.sin()

标签 python pandas fillna

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

相关文章:

python-3.x - 使用fillna在Pandas中用列表填充空值

python - 使用 rml 更改 openerp 7 页眉/页脚

python - 是否可以在现有应用程序中嵌入 Python REST API?

python-2.7 - 数据框中的 Pandas 列表理解

python - 如何在 Python 中粘贴(如 R)和 groupby

python - 如何使用列模式填充 Pandas fillna()?

python - 使用 T5 的句子嵌入

python - trigger.io 工具包在上传私有(private)模块时死机

python - Pandas 将每小时 OHLC 重采样为每日 OHLC

python - 带有条件 python 的部分 fillna