Issue
I have a DataFrame with an index column as [0, 1,2,3]. I would like to change it to ['Q1','Q2','Q3','Q4']. How do I do this? I do not want to introduce a new column but change index only.
I tried qtrs = ['Q1', 'Q2', 'Q3', 'Q4'] and df.reindex(qtrs) where df is the DataFrame.
It does not work!
Solution
You could rewrite the index using a list comprehension:
df.index = [f'Q{(i%4)+1}' for i in df.index]
This might be more sophisticated than you need; it will deal with index values greater than 3. If that's not an issue, just use
df.index = [f'Q{i+1}' for i in df.index]
If your values are actually strings, not integers, you'll have to convert them:
df.index = [f'Q{(int(i)%4)+1}' for i in df.index]
Answered By - Nick
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.