简体   繁体   中英

Rename columns using different rules

I have the following pandas DataFrame:

df =
    --------------------
    0   1   2   3   4
    --------------------
    a   f   45  gt  0.9
    b   f   32  et  1.8

I need to rename columns from 0 1 2 3 4 to f1 f2 f3 target score .

I can rename columns as follows:

df.columns = ["f1" "f2", "f3", "target", "score"]

However, if the number of columns is large, this approach is not suitable.

How can I automate the creation of f1...fN , and then renaming the specific columns (eg 3 and 4 ) manually by index?

If there is always 3+ columns use:

df.columns = [f'f{x+1}' for x in df.columns[:-2]] + ["target", "score"]
print (df)
  f1 f2  f3 target  score
0  a  f  45     gt    0.9
1  b  f  32     et    1.8

If should columns names starting by f0 :

df = df.add_prefix('f')
df.columns.to_numpy()[-2:] = ["target", "score"]
print (df)
  f0 f1  f2 target  score
0  a  f  45     gt    0.9
1  b  f  32     et    1.8 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM