【发布时间】: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