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?
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
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)
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