gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 00:46:20 25 4
gpt4 key购买 nike

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

我不完全确定如何使用 .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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com