python - 对两列应用操作返回 'None'

标签 python pandas

我正在尝试将电子邮件清理功能应用于列,并将结果记录在单独的列中。

我不完全确定如何使用 .apply() 将函数应用到两列,但这是我尝试过的:

首先设置数据框和常见电子邮件错误的字典:

import pandas as pd

df = pd.DataFrame({'emails':['jim@gmailcom','bob@gmail.com','mary@gmaicom','bobby@gmail.com'],
                   'result':['','','','']})

df

    emails          result
0   jim@gmailcom    
1   bob@gmail.com   
2   mary@gmaicom    
3   bobby@gmail.com 

# common mistakes:

correct_domain = {'gmailcom': 'gmail.com',
 'gmaicom': 'gmail.com',
 'gmaillom': 'gmail.com',
 'gmalcom': 'gmail.com'}

现在我想查看电子邮件,并将拼写错误的域名替换为正确的域名。例如。 gmailcom -> gmail.com

def clean_emails(x):

    # for each domain(key) in this dict ( e.g. 'gmailcom':'gmail.com')
    for mistake in correct_domain:  

        # if incorrect domain ('gmailcom') is in the email we're checking
        if mistake  in x['emails']:

            # replace it with the dict value which is the correctly formatted domain ('gmail.com')
            x['emails'] = x['emails'].replace(mistake ,correct_domain[mistake ])

            # record result
            x['result'] = 'email cleaned'

        else:
            x['result'] = 'no cleaning needed'

然后当我应用这个函数时我没有得到:

df.apply(clean_emails,axis=1)

0    None
1    None
2    None
3    None
dtype: object

我尝试在混合中使用return,但无法找出单独列的两个单独的返回值。

我想要的结果,电子邮件已被清理并将结果记录到结果:

    emails          result
0   jim@gmail.com    'email cleaned'    
1   bob@gmail.com   'no cleaning needed'    
2   mary@gmail.com    'email cleaned'   
3   bobby@gmail.com 'no cleaning needed'

编辑:我认为在函数末尾添加 return x 会返回新编辑的行,但电子邮件未清理。

    emails  result
0   jim@gmail.com   email cleaned
1   bob@gmail.com   no cleaning needed
2   mary@gmaicom    no cleaning needed
3   bobby@gmail.com no cleaning needed

最佳答案

使用Series.str.contains检查是否需要清洁 numpy.where按条件查找列,然后使用 Series.str.replace仅用字典替换必要的行的回调:

pat = '|'.join(correct_domain.keys())
m = df['emails'].str.contains(pat, na=False)
df['result'] = np.where(m, 'email cleaned', 'no cleaning needed')
df.loc[m, 'emails'] = (df.loc[m, 'emails']
                         .str.replace(pat, lambda x: correct_domain[x.group()], regex=True))

print (df)
            emails              result
0    jim@gmail.com       email cleaned
1    bob@gmail.com  no cleaning needed
2   mary@gmail.com       email cleaned
3  bobby@gmail.com  no cleaning needed

关于python - 对两列应用操作返回 'None',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56949102/

相关文章:

python - 抓取框架 NTSCtoUSB 加密狗、opencv2、python 包装器

python - 如何在 SQLAlchemy 中仅比较日期时间的日期?

python - 是否可以在没有 DataFrame 的情况下查询 MultiIndex 本身?

python - Numpy 中的线性代数

arrays - 使用掩码数组创建 pandas DataFrame

python - 在 Pandas 中加载通用的 Google 电子表格

python - 如何在 python 中向箱形图添加标签?

python - 本地运行 python 脚本与在 docker 中运行之间的区别

python - 打印字符串中的偶数字符并忽略白色字符串

python - Pandas 按另一列中的值对一列进行排序