skip to Main Content

I have the pandas latest version installed as of now with python version 3.12.0. While running VS Code, I was running this line of code

import pandas as pd

data = pd.DataFrame(np.arange(16).reshape((4,4)),
                    index = ['Ohio', 'Colorado', 'Utah', 'New York'],
                    columns = ['one', 'two', 'three', 'four'])

data.loc['Colorado', ['two', 'three']]

But Pylance is raising error with the squiggly red underline on the last line of code.

The Error says

No overloads for "getitem" match the provided argumentsPylancereportGeneralTypeIssues
frame.pyi(201, 9): Overload 4 is the closest match
Argument of type "tuple[Literal[‘Colorado’], list[str]]" cannot be assigned to parameter "idx" of type "tuple[Scalar, slice]" in function "getitem"
"tuple[Literal[‘Colorado’], list[str]]" is incompatible with "tuple[Scalar, slice]"
Tuple entry 2 is incorrect type
"list[str]" is incompatible with "slice"PylancereportGeneralTypeIssues

But my code runs absolutely fine when executed. I can use "#type: ignore" to supress the warning but can anyone give me a more permanent solution.

Btw this is my first question in Stack overflow.

Edit: I found out my typecheking was on, so turning that off is a solution but if someone has any better solution please tell me.

2

Answers


  1. While using #type: ignore is a quick workaround, you can provide type hints to make it more explicit. In this case, you can use the Union type to indicate that the index can be either a scalar or a list of strings:

    from typing import Union
    
    import pandas as pd
    import numpy as np
    
    data = pd.DataFrame(np.arange(16).reshape((4, 4)),
                        index=['Ohio', 'Colorado', 'Utah', 'New York'],
                        columns=['one', 'two', 'three', 'four'])
    
    # Specify the type of index as Union[Scalar, List[str]]
    index_type: Union[str, list[str]] = 'Colorado'
    columns_type: Union[str, list[str]] = ['two', 'three']
    
    result = data.loc[index_type, columns_type]
    print(result)
    
    Login or Signup to reply.
  2. You could add the following settings to your settings.json in .vscode folder:

      "python.analysis.diagnosticSeverityOverrides": {
        "reportGeneralTypeIssues": "none",
      },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search