0

I made the func for apply as below:

def NewMonth(x):

    if x == 1 or 2:
        return 1
    elif x == 3 or 4:
        return 2
    elif x == 5:
        return 3
    elif x == 6:
        return 4
    elif x == 7 or 8:
        return 5
    elif x == 9 or 10:
        return 6
    elif x == 11 or 12:
        return 7

df_train.apply(lambda y: NewMonth(y['month']), axis=1)

However, all the output I got is '1' among 10,000 row. I can't find what is wrong with my NewMonth func.

Roy
  • 159
  • 3
  • 12

3 Answers3

2

The other solutions solved your problem, but really for this type of calculation you should use .map or pd.cut

Sample Data:

import numpy as np
import pandas as pd
df = pd.DataFrame({'Month': np.random.randint(1,13,10)})

.map

d = {1:1, 2:1, 3:2, 4:2, 5:3, 6:4, 7:5, 8:5, 9:6, 10:6, 11:7, 12:7}
df['Mapped'] = df.Month.map(d)

#   Month  Mapped
#0      3       2
#1      3       2
#2      7       5
#3      2       1
#4      4       2
#5     11       7
#6     12       7
#7     10       6
#8      7       5
#9      2       3

pd.cut

bins = [0,2,4,5,6,8,10,12]  # Right edges
labels= [1,2,3,4,5,6,7]
df['Cut'] = pd.cut(df.Month, bins=bins, labels=labels)

# If want integer labels
# df['Cut'] = pd.cut(df.Month, bins=bins, labels=False)+1 

#   Month  Mapped Cut
#0      3       2   2
#1      3       2   2
#2      7       5   5
#3      2       1   1
#4      4       2   2
#5     11       7   7
#6     12       7   7
#7     10       6   6
#8      7       5   5
#9      2       1   1
ALollz
  • 57,915
  • 7
  • 66
  • 89
  • 1
    Amazing! this is what I search for!! you helped me to save my time, cuz I have to do lots of similar work, like re-classifying month, day, and date, etc based on my list(I guess it would be 'bins' which is made by list). Thanks again! – Roy Nov 15 '18 at 03:14
1

Please change your if condition as :

if x == 1 or x == 2:
Sanchit Kumar
  • 1,545
  • 1
  • 11
  • 19
0

In each if statement, you're currently only comparing x to one number. In the first one, for example, you're saying "if x is 1, or if 2 is true". A number will return True each time, so even though x may not be 1, you will still return 1 every time since 2 will always be true.

It appears what you are trying to do is-

if x == 1 or x == 2
    return 1

And so on.

Hollywood
  • 334
  • 4
  • 17