I have a pandas data frame that consists of special/vanity numbers.
JavaScript
x
5
1
numbers = [539249751,530246444,539246655,539209759,538849098]
2
3
# Create the pandas DataFrame with column name is provided explicitly
4
vanity_class= pd.DataFrame(numbers, columns=['MNM_MOBILE_NUMBER'])
5
I would like to add a column to classify each number based on its pattern using regex
.
I have written a function that iterates through the column MNM_MOBILE_NUMBER
. Identifies the pattern of each number using regex. Then, creates a new column MNC_New_Class
with the relevant classification.
JavaScript
1
15
15
1
def vanity_def(vanity_class):
2
if vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'^5(d)1{7}') |
3
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'^5(?!(d)1)d(d)2{6}$') |
4
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'.{2}(?!(d)1)d(d)2{5}$') |
5
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'^d*(d)(d)(?:12){3}d*$') |
6
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'^5((d)2{3})((d)4{3})$') |
7
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'.{3}(1234567$)'):
8
vanity_class['MNC_New_Class'] = 'Diamond'
9
elif vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'.{3}(?!(d)1)d(d)2{4}$') |
10
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'^(?!(d)1)d((d)3{6})(?!3)d$') |
11
vanity_class.MNM_MOBILE_NUMBER.astype(str).str.match(r'd(d)1(d)2(d)3(d)4'):
12
vanity_class['MNC_New_Class'] = 'Gold'
13
else:
14
vanity_class['MNC_New_Class'] = 'Non Classified'
15
Then, I wrote this line of code to apply the function to the column.
JavaScript
1
2
1
vanity_class['MNC_New_Class'] = vanity_class['MNM_MOBILE_NUMBER'].apply(vanity_def)
2
However, I keep getting this error
AttributeError: ‘int’ object has no attribute ‘MNM_MOBILE_NUMBER’
Any advice on how to avoid this error?
Thank you
Advertisement
Answer
When you pass a function to Pandas’ apply()
, it receives the value of the selected column, not the data frame itself. So you should rewrite your code accordingly:
JavaScript
1
3
1
def vanity_def(mnm_mobile_number): # parameter is an int
2
# return the new value, do the assignment outside of this function
3