astroboy
astroboy

Reputation: 197

How to append two or more columns to one column in the same dataframe

Hello Stack overflow community!

I have a sample data frame here

code      Sum_of_August    Sum_of_September   Sum_of_October
 CC           1000               2000              3000
 AA           9000               8000              6000
 

The column names ['Sum_of_August', 'Sum_of_september','Sum of October'] can also be like ['August Sales', 'September Sales', 'October Sales'].

I have to modify into the following data frame

code      Monthly_target       month      
 CC           1000               8
 AA           9000               8
 CC           2000               9
 AA           8000               9
 CC           3000               10
 AA           6000               10

So I have to convert the column names into month value and append to data frame. I tried for only one month column. But trying to append every month value to new column.

Can anyone help me with this?

Thanks in advance!

Upvotes: 0

Views: 40

Answers (1)

Billy Bonaros
Billy Bonaros

Reputation: 1721

Ok, I have a solution for you. Let's say your data frame is called df.

month = {1:'janauary',
2:'february',
3:'march',
4:'april',
5:'may',
6:'june',
7:'july',
8:'august',
9:'september',
10:'october',
11:'november',
12:'december'}

df=df.melt(id_vars='code')

def month_number(x):
    for i in month:
        if month[i] in x.lower():
            return(i)

df['variable']=df['variable'].apply(month_number)

print(df)

  code  variable  value
0   CC         8   1000
1   AA         8   9000
2   CC         9   2000
3   AA         9   8000
4   CC        10   3000
5   AA        10   6000

Upvotes: 1

Related Questions