簡體   English   中英

為什么 Pandas 中的 KeyError 3

[英]Why KeyError 3 in Pandas

嗨,我不知道為什么我不斷收到此關鍵錯誤,並且數據框看起來像在此處輸入圖像描述

我想找到第一個從加利福尼亞、俄勒岡等地注冊的用戶。所以這是我的代碼

def find_first_user(df):
""" function to find the first user """
    idx = df['user_sign_up_date'].argmin()
    return df.loc[idx, ['user_id', 'user_sign_up_date']]

df.groupby('user_state').apply(find_first_user).sort_values(by='user_sign_up_date')

我不知道哪里出了問題(我已將日期時間全部更改為日期時間類型)。 任何人都有其他方法來解決這個問題或建議?

這是我的解決方案:

  1. 正如我在評論中提到的,您的代碼沒有縮進。
  2. 您使用的 loc function 錯誤:

允許的輸入是:
A single label, eg 5 or 'a', (note that 5 is interpreted as a label of the index, and never as an integer position along the index).
標簽列表或數組,例如 ['a', 'b', 'c']。
帶有標簽的切片 object,例如 'a':'f'。
與被切片的軸長度相同的 boolean 數組,例如 [True, False, True]。
可對齊的 boolean 系列。 鍵的索引將在屏蔽之前對齊。 一個可對齊的索引。 返回選擇的索引將作為輸入。 帶有一個參數(調用 Series 或 DataFrame)的可調用 function 並且 > 返回有效的 output 以進行索引(上述之一)請參閱 ZB021DF6AAC4654C454F46C7764E 選擇的更多信息。

如果未找到任何項目,則引發 KeyError。

很可能是您的 KeyError

From ( https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.DataFrame.loc.html?highlight=loc#pandas.DataFrame.loc )[https://pandas.pydata.org /pandas-docs/stable/reference/api/pandas.DataFrame.loc.html?highlight=loc#pandas.DataFrame.loc]

謝謝我能幫忙。

暫無
暫無

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

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