简体   繁体   English

为什么此代码在 pandas 中引发错误?

[英]Why is this code throwing an error in pandas?

I solve this problem on Stepik: The data frame with the name my_stat contains data with 4 columns: session_value, group, time, n_users.我在 Stepik 上解决了这个问题:名为 my_stat 的数据框包含 4 列数据:session_value、group、time、n_users。 In the variables n_users, we replaced all negative values with the median value of n_users (excluding negative values, of course).在变量 n_users 中,我们将所有负值替换为 n_users 的中值(当然不包括负值)。 Here's what I wrote (I'm new to pandas):这是我写的(我是熊猫的新手):

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()

But when posting the response, I get this error:但是在发布回复时,我收到此错误:

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'

How to fix it?如何解决?

Change your line改变你的线路

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

to this对此

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM