Calle
Calle

Reputation: 153

Adding index to column list python

So I do work on files with over 100 columns using pandas. Each time I need to choose only those I need. So instead of using DataFrame.loc I was thinking about using DataFrame.iloc with specifying only column no.

So I am trying to loop over a list of column names and add an integer that could help me to add the index to each column.

So I have a DataFrame called Data and columns names

['VIN','MODEL','ENGINE']

I would like to return a list of:

['VIN 1','MODEL 2','ENGINE 3']

I tried with the code below and it does basically what I need but the result is not quite alright since it's printing every column name the same number of times as the len(Data.columns)

col_desc = Data.columns

col_list = list(col_desc)

range(len(col_list))

for i in range(len(col_list)):
    for col in col_desc:
        print(col_desc[i] + ' ' + str(i))

Could you suggest any idea to solve this?

Upvotes: 0

Views: 484

Answers (2)

Jarvis
Jarvis

Reputation: 8564

You can do something like this with map and enumerate:

col_list = list(map(lambda x: f"{x[1]} {x[0]}", enumerate(Data.columns, 1)))

Upvotes: 2

Dani Mesejo
Dani Mesejo

Reputation: 61910

You could use enumerate:

# dummy setup
df = pd.DataFrame(columns=['VIN','MODEL','ENGINE'])

# change columns
df.columns = [f'{col} {i}' for i, col in enumerate(df.columns, 1)]

print(df.columns)

Output

Index(['VIN 1', 'MODEL 2', 'ENGINE 3'], dtype='object')

Upvotes: 4

Related Questions