为什么此代码在 pandas 中抛出错误?

Why is this code throwing an error in pandas?

我试图在 Stepik 上解决这个问题:名称为 my_stat 的数据框包含 4 列:session_valuegrouptimen_users。在变量n_users中,我们将所有负值替换为n_users的中值(当然不包括负值)。这是我写的:

import pandas as pd    
import numpy as np

my_stat = my_stat['session_value'].replace(np.nan, 0)
my_stat.loc[my_stat['n_users'] < 0, 'n_users'] = my_stat['n_users'].median()

但是我得到这个错误:

Error:
Traceback (most recent call last):
  File "jailed_code", line 25, in <module>
    med = my_stat['n_users'].median()
  File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/pandas/core/series.py", line 871, in __getitem__
    result = self.index.get_value(self, key)
  File "/home/stepic/instances/master-plugins/sandbox/python3/lib/python3.6/site-packages/pandas/core/indexes/base.py", line 4405, in get_value
    return self._engine.get_value(s, k, tz=getattr(series.dtype, "tz", None))
  File "pandas/_libs/index.pyx", line 80, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 90, in pandas._libs.index.IndexEngine.get_value
  File "pandas/_libs/index.pyx", line 135, in pandas._libs.index.IndexEngine.get_loc
  File "pandas/_libs/index_class_helper.pxi", line 109, in pandas._libs.index.Int64Engine._check_type
KeyError: 'n_users'

我该如何解决?

换行

my_stat = my_stat['session_value'].replace(np.nan, 0)

至此

my_stat['session_value'] = my_stat['session_value'].replace(np.nan, 0)

或者,更好的是,使用 fillna:

my_stat['session_value'] = my_stat['session_value'].fillna(0)