Search code examples
pythonpandasserieskeyerror

Why is there a KEY ERROR in one place but no KEY ERROR in another similar statement?


I made a PANDAS Series in the first line of the code below. But I can't understand why there is an error in the 3rd line but no error in the 2nd line. Please run the code in Jupyter in 3 separate blocks and help me if you understood the cause of error in 3rd line.

data = pd.Series([1,2,3,4,5], index=['a', 'b', 'c', 7, 8])
data['g']=5 # NO ERROR.
data[9] = 7 # WHY ERROR ??

Solution

  • You need to use the pandas loc() function to avoid this error:

    import pandas as pd
    
    data = pd.Series([1,2,3,4,5], index=['a', 'b', 'c', 7, 8])
    data['g'] = 5
    data.loc[9] = 7
    print(data)
    

    Output:

    a    1
    b    2
    c    3
    7    4
    8    5
    g    5
    9    7
    dtype: int64