Issue
I'm new to programming, currently trying to refactor this piece of code, the function of this chunk of codes is to replace the whitespace in the column names with '_', here's the codes:
labels = list(df.columns)
labels[0] = labels[0].replace(' ', '_')
labels[1] = labels[1].replace(' ', '_')
labels[2] = labels[2].replace(' ', '_')
labels[3] = labels[3].replace(' ', '_')
labels[5] = labels[5].replace(' ', '_')
labels[6] = labels[6].replace(' ', '_')
df.columns = labels
How can I refactor it and maybe make it reusable? Thanks in advance.
Solution
Try this:
def fun(label):
return label.replace(' ', '_')
df.columns = map(fun, df.columns)
Answered By - deadshot
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.