簡體   English   中英

為什么此代碼在 pandas 中引發錯誤?

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

我在 Stepik 上解決了這個問題:名為 my_stat 的數據框包含 4 列數據:session_value、group、time、n_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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM