Mactilda
Mactilda

Reputation: 393

Getting the column "number" and column name to make it easier to select several - not always adjacent - columns in a large df in pandas

I have a large df that I'd like to do calculation and predictions from, the problem is that I can't find a way to get a list of all column names TOGETHER with the column "number". I'ts impossible to count from the top to see which number it is, and I'd rather not write out all the column names.
It would be nice to be able to use something like this:
df.iloc[:, np.r_[2, 5:10, 22:102, 109:129]]
but for that to work I need to know which column has what number.
list(df)gives me a nice list, but without the numbers which makes it pointless in this quest.

Upvotes: 1

Views: 37

Answers (1)

jezrael
jezrael

Reputation: 863301

I suggest to create dictionary with enumerate:

df = pd.DataFrame({
        'A':list('abcdef'),
         'B':[4,5,4,5,5,4],
         'C':[7,8.0,9,4.0,2,3],
         'D':[1,3,5,7,1,0],
         'E':[5,3,6,9,2,4],
         'F':list('aaabbb')
})

d = dict(enumerate(df))
print (d)
{0: 'A', 1: 'B', 2: 'C', 3: 'D', 4: 'E', 5: 'F'}

Or list of tuples like suggested @Chris in comments:

L = list(enumerate(df))
print (L)
[(0, 'A'), (1, 'B'), (2, 'C'), (3, 'D'), (4, 'E'), (5, 'F')]

Upvotes: 2

Related Questions