【发布时间】:2021-04-04 21:39:23
【问题描述】:
我正在尝试制作一个与下面的.apply 方法具有相同目的的 Pandas 矢量化脚本:
concised_df['email_account_letter_or_number_only'] = concised_df.apply(lambda x: x['email_account'] if (str(x['email_account']).isdigit() or not bool(re.search('[a-zA-Z]', str(x['email_account'])))) else (re.sub('[^A-Za-z]+', '', x['email_account'])), axis=1)
代码的逻辑是这样的:如果email_account 是全数字或者不包含字母,那么只需将email_account 存储为email_account_letter_or_number_only。否则,执行re.sub 以仅保留email_account_letter_or_number_only 的字母(换句话说,删除所有数字和特殊字符)。
我尝试使 Pandas 矢量化的原因是为了使我的方法更加优化。如本博客https://towardsdatascience.com/apply-function-to-pandas-dataframe-rows-76df74165ee4(方法6.矢量化)所述,Pandas 矢量化比.apply 快得多。
这是我想要的输入和输出示例:
| email_account | email_account_letter_or_number_only |
|---|---|
| 0018889 | 0018889 |
| nacho.taro | nachotaro |
| nachth45678 | nachth |
| nacikita | nacikita |
| nacia_art | naciaart |
我尝试过 Goole 搜索“带有 if else 条件的 Pandas 矢量化”,但到目前为止我能够找到的结果都引用了其他方法,例如 numpy.where 或 pd.DataFrame.loc (How to iterate a vectorized if/else statement over additional columns?) 而不是 Pandas 矢量化。
【问题讨论】:
-
我知道这是后续行动,但如果您希望有人为您提供最佳解决方案,他们首先需要了解您的问题以及您正在使用的数据。首先提供 5-10 行数据作为文本(请不要使用图像),并提供预期的输出。还要解释代码试图做什么。代码漫游,数据讨论。
-
有道理,@cs95。我正要跟进示例输出表,但我看到您或 Nick 已将表添加到其中。谢谢。我现在将在我的代码中添加更多描述。
-
好的,试试
df['email_account_letter_or_number_only'] = np.where(df['email_account'].str.isdigit(), df['email_account'], df['email_account'].str.replace(r'[\W_]+', ''))np.where是相当矢量化的。 -
@cs95 但它输出
['0018889', 'nachotaro', 'nachth45678', 'nacikita', 'naciaart'],因为'nachth45678'不匹配only keep letters (in other words, remove all numbers and special characters) for email_account_letter_or_number_only. -
np.where(df['email_account'].str.isdigit(), df['email_account'], df['email_account'].str.replace(r'[\W_\d ]+', ''))
标签: python regex pandas string