Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

efficient way to subset and rename data.frame columns together in Python

Tags:

python

pandas

In R data.table you can subset and rename columns at the same time. You can also select a column multiple times and rename it at the time of selection. Extremely fast and convenient. Can you do the same thing in Python? So far, all i have been able to do is separately selecting and renaming columns. It's really a pain for such a simple operation!

For example, my data.table DT has four columns A, B, C, D. in R you can:

subset_DT = DT[,.(A, B, second_A = A, rename_D = D)]

This subsets columns A, B, A, D and at the same time renames the second A and D columns to second_A and rename_D columns. So that subset_DT would have four columns; A, B, second_A, rename_D.

how can I do this neatly (in one straight forward operation) in Python pandas without separating the subset and renaming operations?

like image 260
Ankhnesmerira Avatar asked Jan 29 '26 20:01

Ankhnesmerira


1 Answers

try the following code:

df=df.rename(columns = {'second_A':'A','rename_D':'D'})
like image 106
oreopot Avatar answered Jan 31 '26 09:01

oreopot