3

The column of the dataframe df is multi-indexed.

>>>df
    c1      c2    
    d1  d2  d1  d2
r1  11  12  21  22

Therefore, with the code list(df.columns.levels[0] a list of ['c1', 'c2'] is created. The following code can run without error. But PyCharm marks levels in the line print(list(df.columns.levels[0])) as a warning Unresolved attribute reference 'levels' for class 'Index'.

I think it could be solved by more specific type hinting in the function signature of print_columns. In the code below, I only use the type df: pd.DataFrame. PyCharm thinks it is a simple dataframe without multi-index.

Could you please show me how to improve the type hint? Or do you have other solutions to remove the warning from PyCharm?

Thanks.

import pandas as pd


def get_df() -> pd.DataFrame:
    data = {
        ('c1', 'd1'): [11],
        ('c1', 'd2'): [12],
        ('c2', 'd1'): [21],
        ('c2', 'd2'): [22],
    }

    df = pd.DataFrame.from_dict(data)
    df.index = ['r1']
    return df


def print_columns(df: pd.DataFrame):
    print(list(df.columns.levels[0]))  # prints ['c1', 'c2']


if __name__ == '__main__':
    df_ = get_df()
    print_columns(df=df_)

aura
  • 383
  • 7
  • 24

0 Answers0