【问题标题】:Assign Values in Column from Substring从子字符串分配列中的值
【发布时间】:2019-12-17 07:35:50
【问题描述】:

我是 Pandas 的新手,很难找出解决以下问题的最佳方法:

我有一个 Dataframe,其中有一列名为 Email,如下所示:

Email
abc@yahoo.com
defg@gmail.com
NAN
ghi@yahoo.com
jkl@gmail.com.it

我将“@”上的字符串分开以创建域列,并希望使用该列在新列中分配关键字。例如,如果域包含单词“yahoo”,则在新列中将其命名为“Yahoo Account”。如果它不包含单词“yahoo”,则为其分配值“Other Domain”,如果它是 NaN,则将其称为“Unknown”。

名为 Affiliation 的新列如下所示:

Affiliation 
Yahoo Account 
Other Domain 
Unknown 
Yahoo Account 
Other Domain

有超过 2,000 种不同类型的域,因此我正在寻找一种方法,我不会将所有唯一域列出和映射为“雅虎帐户”或“其他域”。

我研究了几个选项,其中之一是 where 子句,但它将 NaN 值分配给 Other Domain 关键字。

df['Affiliation'] = np.where(df['Domain']=='yahoo', 'Yahoo Account', 'Other Domain')

我也开始考虑使用替换子句,但由于需要将大量唯一域添加到 other_affiliations,因此我认为这不是最好的方法。见下文:

yahoo_affiliations = (r'(yahoo\S*)')
other_affiliations= (r'(gmail\S*)|(hotmail\S*)|(outlook\S*)')

# Create a new column called Affiliation from Domains
df['Affiliation'] = df['Domain']

# Fill NaN with Unknwon
df['Affiliation']  = df['Affiliation'].fillna('Unknown')

replacements = {
           'Affiliation': {yahoo_affiliations: 'Yahoo Account',
                                        other_affiliations: 'Other Domain'}
                        }

df.replace(replacements, regex=True, inplace=True)

【问题讨论】:

  • 你已经成功地分离了字符串?你能更具体地说明问题是什么吗?你读过 Pandas 文档吗?
  • 是的,我已经查看了文档和 StackOverflow 上的内容 - 我只是想进一步澄清一下。感谢您询问更多信息!
  • opressionslayer的回答好吗?顺便说一下,您不需要将中间系列分配给您的 DataFrame,我认为他这样做只是为了清楚起见。

标签: python python-3.x pandas


【解决方案1】:

您可以像这样拆分它们以获取映射

email_map = {'yahoo.com': 'Yahoo Account',
'gmail.com': 'Other Domain',
'gmail.com.it': 'Other Domain' 
}
dfa['domain'] = dfa['Email'].str.extract(r'.*?@(.*)') 
dfa['Affiliation'] = dfa['domain'].map(email_map).fillna('Unknown') 

输出:

              Email        domain    Affiliation
0     abc@yahoo.com     yahoo.com  Yahoo Account
1     def@gmail.com     gmail.com   Other Domain
2               NAN           NaN        Unknown
3     ghi@yahoo.com     yahoo.com  Yahoo Account
4  jkl@gmail.com.it  gmail.com.it   Other Domain

【讨论】:

  • 感谢压迫者!我希望避免创建类似 email_map 的内容,因为我必须将 2,000 多个唯一域分配给“其他域”。看到您的回复后,我意识到这并不明显,因此编辑了我的问题!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2023-03-28
  • 1970-01-01
  • 2019-07-27
  • 1970-01-01
  • 2019-05-22
  • 2019-09-08
  • 1970-01-01
相关资源
最近更新 更多