如何计算反应不同的页面基于一个月从CSV与Python熊猫?



我有一个CSV文件,我用Pandas读过。我需要计算在给定月份(例如在5月份)有多少不同的用户喜欢每个页面。

下面是一个关于我的CSV的示例:

username,page,date
usera,sample1,2021-05-04
userb,sample1,2021-05-04
usera,sample1,2021-05-05
userd,sample2,2021-05-06
userc,sample2,2021-05-07
userc,sample2,2021-05-08
userc,sample2,2021-05-09
userf,sample2,2021-05-09
userx,sample2,2021-06-01
sample1 2 users liked in 05 month
sample2 3 users liked in 05 month 

这是我的样本代码,我不知道如何过滤到一个特定的日期?

import pandas as pd
df = pd.read_csv("sample.csv")
print(df.groupby(['page']).size().reset_index(name='username'))

这段代码是否以正确的方式过滤了不同的用户和页面?你能帮我把日期也过滤一下吗?

使用pd.to_datetimedate列转换为日期时间,这样您就可以在分组数据框时使用访问器对象(dt.month)来获取类似日期时间的值。使用drop_duplicates只获取在给定月份喜欢每个页面的唯一用户。然后,使用apply(len)计算每个页面有多少不同的用户喜欢。从这里开始,您可以使用reset_index将索引作为列(这将有助于构建输出字符串),并使用iterrows遍历每一行,以所需的格式打印消息。

import pandas as pd
df = pd.read_csv("sample.csv")
# convert to datetime to use 'dt.month' in the groupby
df['date'] = pd.to_datetime(df['date'])
df = df.drop_duplicates(['page', 'username'])
g = df.groupby(['page', df['date'].dt.month])
# count how many different users liked each page in a given month
page_count = g.apply(len)
page_date_cnt = page_count.reset_index(level=[0,1])
for idx, frame in page_date_cnt.iterrows():
print(f"{frame['page']}: {frame[0]} users liked in {frame['date']:02} month")

输出:

sample1: 2 users liked in 05 month
sample2: 3 users liked in 05 month
sample2: 1 users liked in 06 month

相关内容

最新更新