Tjs*_*s01 1 python group-by dataframe pandas
我有一个包含以下元素的列表:
emails= ['xyz.com', 'abc.com','def.com']
Run Code Online (Sandbox Code Playgroud)
现在,我有一个数据框,如下所示:
df:
UserID Email_Address
U001 u001@abc.com
U002 u002@xyz.com
U003 u003@xyz.com
U004 u004@abc.com
U004 u005@def.com
U006 u006@def.com
U007 u007@def.com
Run Code Online (Sandbox Code Playgroud)
我想根据子字符串对 groupby 执行计数,其中子字符串是列表中的元素。
因此,输出应如下所示:
abc.com 2
def.com 3
xyz.com 2
Run Code Online (Sandbox Code Playgroud)
我当前的代码:
for domain in list1:
count = df.groupby( [df.Email_Address.str.find(domain)]).sum()
Run Code Online (Sandbox Code Playgroud)
用于Series.str.extract通过列表获取值并通过 聚合GroupBy.size:
pat = '|'.join(emails)
s = df['Email_Address'].str.extract('('+ pat + ')', expand=False)
df1 = df.groupby(s).size().reset_index(name='Count')
print (df1)
Email_Address Count
0 abc.com 2
1 def.com 3
2 xyz.com 2
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9162 次 |
| 最近记录: |