在数据帧上应用函数将不起作用,函数中的AttributeError错误

2024-06-06 15:49:22 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试应用一个函数,它将返回“清理”的电子邮件值。然而,我很难将我的函数应用于我受人尊敬的专栏

请推荐最佳方法

样本数据:

sample_data= {'email': ['Sam@mail.com','Sam@mail.com',
                        'Doug@mail.com', 'Doug@mail.com',
                       np.NAN, np.NAN],
              'price': [25.95, 31.25, 34.95, 19.95, 59.95, 15.75]}

sample_df = pd.DataFrame(sample_data)

# print(sample_df)
    email   price
0   Sam@mail.com    25.95
1   Sam@mail.com    31.25
2   Doug@mail.com   34.95
3   Doug@mail.com   19.95
4   NaN     59.95
5   NaN     15.75

应用函数:

def clean_emails(s):
    emails = {x: str(x).lower() for x in s.unique()}
    return s.map(emails)

# Passing the column directly into the function works
sample_df.email = clean_emails(sample_df.email)

# So does passing the entire df into an apply statement
sample_df = sample_df.apply(clean_emails)

print(sample_df)

    email   price
0   sam@mail.com    25.95
1   sam@mail.com    31.25
2   doug@mail.com   34.95
3   doug@mail.com   19.95
4   nan     59.95
5   nan     15.75

如前所示,将列直接传递到函数中是可行的。应用整个df也是如此。我关心的是更大的数据集,将单个列传递给函数

总之,将df的一列传递给函数是解决这个问题的最佳方法吗?或者可以使用apply


Tags: the数据sample方法函数cleancomdf
1条回答
网友
1楼 · 发布于 2024-06-06 15:49:22

您使用的函数是unique(),它不是数据帧的属性。看来你是想把它应用到系列上,而不是数据帧上

有几件事要记住

  1. 函数将str应用于NaN值,并将它们转换为pd.isnull无法识别的字符串。我想你不想那样
  2. 我忘了:)
import numpy as np
import pandas as pd

sample_data= pd.DataFrame({'email': ['Sam@mail.com','Sam@mail.com', 'Doug@mail.com', 'Doug@mail.com', np.NAN, np.NAN],
'price': [25.95, 31.25, 34.95, 19.95, 59.95, 15.75]})

sample_data.email =  sample_data.email.str.lower()

你也可以这样做

email_dict = {el: el.lower() for el in sample_data.email.unique() if pd.notnull(el)}
sample_data.email = sample_data.email.replace(email_dict)

相关问题 更多 >