how to loop through columns of a dataframe which have intezers as column names

I have a dataframe with column names as 1,2,3,4..10 . I have sub category of columns as

sub_cols = ['1','2','3']

I want to loop through these sub_cols

for col in sub_cols:
    print('column: '+str(col))
    data[col]
    len(data[col])

I get an output

column: 1
column: 2
column: 3

but data of columns or len of columns is not printed. I don't see any error too. Where am I going wrong?

2 answers

  • answered 2021-05-15 17:54 Corralien

    Your code corrected:

    for col in sub_cols:
        print('column: '+str(col))
        print(data[col])
        print(len(data[col])
    

  • answered 2021-05-15 18:03 Rob Raymond

    Looks like your fundamental issue if you list of integers is a list of strings.

    • following code shows how to loop through columns where name is an integer
    • simple list comprehension with isinstance(c, int)
    cols = [i for i in range(5)]+list("abcd")
    df = pd.DataFrame(np.random.randint(1,5,5*len(cols)).reshape(5,len(cols)), columns=cols)
    df.loc[:,[c for c in df.columns if isinstance(c, int)]]
    
    

    df

    0 1 2 3 4 a b c d
    0 3 4 1 2 4 4 4 1 4
    1 1 4 3 2 1 2 4 4 1
    2 2 3 4 1 1 4 4 4 2
    3 3 1 3 1 2 4 2 4 3
    4 3 4 1 4 1 4 1 1 1

    df.loc[:,[c for c in df.columns if isinstance(c, int)]]

    0 1 2 3 4
    0 3 4 1 2 4
    1 1 4 3 2 1
    2 2 3 4 1 1
    3 3 1 3 1 2
    4 3 4 1 4 1