PythonPandas统计

2024-04-25 05:03:57 发布

您现在位置:Python中文网/ 问答频道 /正文

         user_id  report_date  tBalance  yBalance  total_purchase_amt  
0              3     20131106         0         0                   0   
1              4     20140726         0         0             5119808   
2              5     20131029       153       153                   0   
3              5     20141101    196254    196229                  25   
4              5     20141104    196329    196304                  25   
5              5     20131107    179600    179577                  23   
6              5     20131110    159834    159814                  20   

一个我的数据样本,我想找出每个新用户的条目月份例如,users 3在2013011首次出现,但没有出现在那之前我要这个条目

user_id  report_date  tBalance  yBalance       total_purchase_amt  
   3     20131106         0         0              0   

Tags: 数据用户reportiddate条目purchaseusers
2条回答

我想我明白你的问题了。在本例中,我使用掩码来获取一系列在特定月份登录的用户和一系列在其他月份登录的用户。 然后,我比较这两个系列,选择只出现在第一个系列中的用户。你知道吗

在这个例子中,我构建了一个1.数据帧从制表符分隔的文件输入文件“我复制了你的输入。你知道吗

import pandas

df = pandas.read_table('input.txt').astype(int)
target_month = 20131100 #yyyymmdd the month starts at day 00

mask_1 = df.report_date > target_month
mask_2 = df.report_date < (target_month + 100) #adding 100 changes the month

subset_1 = df[mask_1 & mask_2].groupby(['user_id']) # all users showed up during the target month


mask_3 = df.report_date < target_month
mask_4 = df.report_date > (target_month + 100)

subset_2 = df[mask_3 | mask_4].groupby(['user_id']) # all users showed up in other months


new_users = []
for item in subset_1['user_id']:
    for user in list(item[1]):
        if user not in new_users:
            new_users += [user]

for item in subset_2['user_id']:
    for user in list(item[1]):
        if user in new_users:
            new_users.remove(user)

output = df[df.user_id.isin(new_users)]
print(output)

输出为:

         user_id  report_date  tBalance  yBalance  total_purchase_amt  
0              3     20131106         0         0                   0

据我所知,您想要的条目将以2013011(而不是20131106)作为报告日期?你每个月都要这条线吗?你知道吗

如果是这样,我只需要为每个用户取第一个发生月份:

  1. 将报表日期转换为日期格式,只保留月份(和年份),我们称之为报表日期月份

  2. 为每个用户创建一个数据框,将其在表中出现的第一个日期关联起来:

    df2 = df[['user_id','report_date_month']].groupby('user_id').min()
    
  3. 重置索引以访问您的组(用户id):

    df2.reset_index(inplace=True)
    
  4. 按月分组并统计用户数:

    df2.groupby('report_date_month').count()
    

这将为您提供一个2列的数据框,其中包含每个月出现的用户数

相关问题 更多 >