I have a fairly huge DataFrame (~500 columns and >5000 rows). I want to add a prefix to the first 15 columns. I found a function called add_prefix()
that can set a prefix to all columns at once. I tried the following:
df[df.columns[range(0,15)]] = df[df.columns[range(0,15)]].add_prefix('f_')
with 'f_'
being the prefix I would like to add. Yet, the output doesn't seem to change.
>>>
mean std var ... 525 526 label
0 -2.546261 17.827072 317.804485 ... -0.314016 -0.310878 0.0
1 -2.338710 17.915556 320.967136 ... -0.345603 -0.343088 0.0
2 -2.095051 17.539407 307.630788 ... -0.323596 -0.324990 0.0
3 -1.685209 18.257797 333.347150 ... -0.310060 -0.320796 0.0
4 -1.846169 17.240523 297.235618 ... -0.318660 -0.322732 0.0
What I would like to have is:
>>>
f_mean f_std f_var ... 525 526 label
0 -2.546261 17.827072 317.804485 ... -0.314016 -0.310878 0.0
1 -2.338710 17.915556 320.967136 ... -0.345603 -0.343088 0.0
2 -2.095051 17.539407 307.630788 ... -0.323596 -0.324990 0.0
3 -1.685209 18.257797 333.347150 ... -0.310060 -0.320796 0.0
4 -1.846169 17.240523 297.235618 ... -0.318660 -0.322732 0.0
What am I doing wrong?
You cannot directly assign a prefix as you are currently doing it, given that indices do not support mutable operations. So you would have to reassign all columns again. Here's one way to do it with a list comprehension:
df.columns = ['f_' + i if ix < 15 else i for ix, i in enumerate(df.columns)]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With