AxW
AxW

Reputation: 662

Rename multiple columns by index using an iterative name in pandas

Apologies if something similar has been asked before, I searched around but couldn't figure out a solution.

I have a dataframe like such:

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

I want to rename columns of this dataframe, say, indices [:,1:2] which are B and C in this case, into something with an iterating pattern.

Such as new column names:

A Q1 Q2 D E

There is a prefix and the 1, 2, etc can auto-increment based on the range. An added bonus would be if I could also control the string portion, such that I could get: (given I provide a list with possible entries like =

names = ['Dog','Cat']

A QDog1 QCat2 D E

Any help is appreciated, thanks!

Upvotes: 3

Views: 713

Answers (4)

Mykola Zotko
Mykola Zotko

Reputation: 17824

You can use the method rename with a dictionary:

names = iter(['Dog','Cat'])
dct = {col: f'Q{next(names)}{num}' for num, col in enumerate(df.columns[1:3], 1)}
# {'B': 'QDog1', 'C': 'QCat2'}

df.rename(columns=dct, inplace=True)

Output:

   A  QDog1  QCat2  D  E
0  a      4      7  1  a
1  b      5      8  3  a
2  c      4      9  5  a
3  d      5      4  7  b
4  e      5      2  1  b
5  f      4      3  0  b

Upvotes: 0

anky
anky

Reputation: 75080

If you are looking to modify the original column names and not return a copy, once can also do:

names = ['Dog','Cat']
df.columns.to_numpy()[1:3] = [f'Q{b}{a}' for a,b in enumerate(names,1)]

Earlier verbose version:

names = ['Dog','Cat']
idx = df.columns.to_numpy()
idx[1:3] = [f'Q{b}{a}' for a,b in enumerate(names,1)]
df.columns= idx

print(df)

   A  QDog1  QCat2  D  E
0  a      4      7  1  a
1  b      5      8  3  a
2  c      4      9  5  a
3  d      5      4  7  b
4  e      5      2  1  b
5  f      4      3  0  b

Upvotes: 1

Epsi95
Epsi95

Reputation: 9047

You can iterate over it to change the names. Change the range to get your desired range like ...numerate(df.columns[1:3])..

names = ['Dog','Cat']

for index, column_name in enumerate(df.columns[1:3]):
    df.rename(columns={column_name: f'Q{names[index]}{index+1}'}, inplace=True)

output

    A   QDog1   QCat2   D   E
0   a   4   7   1   a
1   b   5   8   3   a
2   c   4   9   5   a
3   d   5   4   7   b
4   e   5   2   1   b
5   f   4   3   0   b

Upvotes: 3

Naivre
Naivre

Reputation: 97

You can create a list_of_names and after use columns property:

list_of_name = [your code here]
df.columns = list_of_names

Upvotes: 0

Related Questions