Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to rename a specific range of columns in Python (Pandas)

 KOAK.rename(columns = lambda x : 'KOAK-' + x, inplace=True)

The above code allows me to add 'KOAK' in front of all column headers in my data frame but I only want to add the KOAK prefix to column numbers 4-38. How would I go about doing this?

like image 906
PrimeMet Avatar asked Sep 18 '25 11:09

PrimeMet


2 Answers

You can assign to columns:

KOAK.columns = ['KOAK-' + x if 4 <= i <= 38 else x for i, x in enumerate(KOAK.columns, 1)]

Example:

KOAK = pd.DataFrame(dict.fromkeys('ABCDEFG', [12]))
KOAK.columns = ['KOAK-' + x if 2 <= i <= 4 else x 
                for i, x in enumerate(KOAK.columns, 1)]
print(KOAK)

Prints:

    A  KOAK-B  KOAK-C  KOAK-D   E   F   G
0  12      12      12      12  12  12  12
like image 70
Mike Müller Avatar answered Sep 20 '25 03:09

Mike Müller


You can create a dict by zipping the column ordinal range with a list comprehension and passing this to rename:

In [2]:
df = pd.DataFrame(columns=list('abcdefg'))
df

Out[2]:
Empty DataFrame
Columns: [a, b, c, d, e, f, g]
Index: []

In [3]:
new_cols = dict(zip(df.columns[2:5], ['KOAK-' + x for x in df.columns[2:5]]))
new_cols

Out[3]:
{'c': 'KOAK-c', 'd': 'KOAK-d', 'e': 'KOAK-e'}

In [6]:    
df.rename(columns= new_cols, inplace=True)
df

Out[6]:
Empty DataFrame
Columns: [a, b, KOAK-c, KOAK-d, KOAK-e, f, g]
Index: []

so in your care the following should work:

new_cols = dict(zip(df.columns[3:47], ['KOAK-' + str(x) for x in df.columns[3:47]]))
df.rename(columns= new_cols, inplace=True)
like image 36
EdChum Avatar answered Sep 20 '25 02:09

EdChum