1

I have the following data:

S.No   Department  stock stock  stock
1       Medicine        34  38  58
2       Pharma          23  39  71
3       ortho           76  12  81

The source file I am getting has the repeated values of column headers as "stock", it actually should be "Stock1", "Stock2" and "Stock3". I do not want to do it manually but programmatically.

I tried:

df.rename(columns  = {df.columns[1]: 'Stock1'})
df.rename(columns  = {df.columns[2]: 'Stock2'})
df.rename(columns  = {df.columns[3]: 'Stock3'})

But this does not work.

Please help.

2 Answers 2

1

Several points of failure.

  1. The pandas.DataFrame.rename method returns a copy. You need to reassign it back to the name df
  2. You should be doing it with one dictionary
  3. That wouldn't work because you have three columns named the same thing

I have to assume some things about the general form of your problem. First, I'll split your dataframe up into columns with 'stock' and columns without

df_stock = df.filter(regex='^stock$')
df_other = df.drop('stock', axis=1)

df_stock.columns += list(map(str, range(1, df_stock.shape[1] + 1)))

df_new = df_other.join(df_stock)
Sign up to request clarification or add additional context in comments.

8 Comments

After the split, what do you suggest should be done to achieve the result ??
df_new is the result
Actually in the second line of code ( df_other = df.drop('stock', axis=1)) , it throws an error saying: Expected Tuple, got a string
@zsh_18 I’ll have to look at it tomorrow
No worries. Many Thanks
|
0

Have you tried df.columns=['Stock1', 'Stock2', 'Stock3']?

1 Comment

The reason I do not prefer doing this is, if the source file changes the first column to the last it still names the column in the same sequence. While the renaming column makes sure that where ever the position of that column is, it gets renamed right.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.