Python lambda中的条件不返回所需结果
我试图使用lambda根据数字长度组织许多电话号码,但我的条件语句似乎没有正确读取df。目前,它返回的所有内容都是false,我希望它做的是查看列长度,获取数字,检查该数字是否等于10,并应用格式。字符串格式在条件状态下工作,但是我的字符串长度范围为0-15个字符,所有这些字符都需要单独的格式,因此我希望它检查数字的列长度,并适当地应用格式。现在我只是想让10位数的数字发挥作用Python lambda中的条件不返回所需结果,python,pandas,Python,Pandas,我试图使用lambda根据数字长度组织许多电话号码,但我的条件语句似乎没有正确读取df。目前,它返回的所有内容都是false,我希望它做的是查看列长度,获取数字,检查该数字是否等于10,并应用格式。字符串格式在条件状态下工作,但是我的字符串长度范围为0-15个字符,所有这些字符都需要单独的格式,因此我希望它检查数字的列长度,并适当地应用格式。现在我只是想让10位数的数字发挥作用 Phone['Phone Number'] = Phone['Phone Number'].str.replace('
Phone['Phone Number'] = Phone['Phone Number'].str.replace(' ', '')
#Sorts Phone Number by length
Phone.index = Phone['Phone Number'].str.len()
PhoneLength = Phone.sort_index(ascending=False).reset_index(drop=True)
#Creates Table with Phone Numbers Number of Digits in Phone PhoneLength
Phone['Length'] = Phone['Phone Number'].str.len()
PhoneLength.sort_values('Length', ascending=False, inplace=True)
PhoneLength['Correct']=PhoneLength['Phone Number'].astype(str).apply(lambda x: ('('+x[:3]+')'+x[3:6]+'-'+x[6:10]) if ['Length'] == (10) else print ('False'))
我想要它做什么
Phone Number Length Correct
0 1151464301 10 Correctly Formatted Number Here
2 1919772014 10 Correctly Formatted Number Here
3 1919472011 10 Correctly Formatted Number Here
4 2484731500 10 Correctly Formatted Number Here
请尝试以下操作:
Phone.apply(lambda x: ('('+str(x['Phone Number'])[:3]+')'+str(x['Phone Number'])[3:6]+'-'+str(x['Phone Number'])[6:10]) if x['Length'] == 10 else 'False', axis = 1)
上述方法的问题在于,应用函数仅位于PhoneLength['Phone Number']列上。“长度”列不可用。可以使用与初始尝试类似的方法重新计算长度列:
Phone['Phone Number'].astype('str').apply(lambda x: ('('+x[:3]+')'+x[3:6]+'-'+x[6:10]) if len(x) == 10 else 'False')
解决此问题的方法如下所示:
# Create a DataFrame
Phone = pd.DataFrame({'Phone Number':['312 422 3344', '432 345 33444']})
# Remove space character
Phone['Phone Number'] = Phone['Phone Number'].str.replace(' ', '')
# Create a new column "Length" and sort "Phone Number" by "Length"
Phone['Length'] = Phone['Phone Number'].str.len()
Phone.sort_values(by = 'Length', ascending = False, inplace = True)
# Create a new column: Correct
Phone['Correct'] = Phone[Phone['Length']==10]['Phone Number'].apply(lambda x: ('('+x[:3]+')'+x[3:6]+'-'+x[6:10]))
您可以将最后一行代码放入不同长度的for循环中,就完成了。一个简洁的方法是定义一个函数。您能添加一些输入数据以便我们可以复制代码吗?