在具有相同结尾的组内填充数据框上的日期

如何解决在具有相同结尾的组内填充数据框上的日期

这就是我所拥有的:

df = pd.DataFrame({'item': [1,1,2,1],'shop': ['A','A','B','B'],'date': pd.to_datetime(['2018.01.'+ str(x) for x in [2,3,4,5]]),'qty': [5,6,7,8,9,10]})
print(df)

   item shop       date  qty
0     1    A 2018-01-02    5
1     1    A 2018-01-03    6
2     2    A 2018-01-01    7
3     2    A 2018-01-04    8
4     1    B 2018-01-04    9
5     1    B 2018-01-05   10

这就是我想要的:

out = pd.DataFrame({'item': [1,5,10]})
print(out)

    item shop       date  qty
0      1    A 2018-01-02    5
1      1    A 2018-01-03    6
2      1    A 2018-01-04    0
3      1    A 2018-01-05    0
4      2    A 2018-01-01    7
5      2    A 2018-01-02    0
6      2    A 2018-01-03    0
7      2    A 2018-01-04    8
8      2    A 2018-01-05    0
9      1    B 2018-01-04    9
10     1    B 2018-01-05   10

这是我目前取得的成就:

df.set_index('date').groupby(['item','shop']).resample("D")['qty'].sum().reset_index(name='qty')

   item shop       date  qty
0     1    A 2018-01-02    5
1     1    A 2018-01-03    6
2     1    B 2018-01-04    9
3     1    B 2018-01-05   10
4     2    A 2018-01-01    7
5     2    A 2018-01-02    0
6     2    A 2018-01-03    0
7     2    A 2018-01-04    8

我想完成缺失的日期(按天!),以便每个组 [item-shop] 都以相同的日期结束。

想法?

解决方法

这里的关键是在不同的组内创建minmax,然后我们创建范围和explode merge返回

# find the min date for each shop under each item
s = df.groupby(['item','shop'])[['date']].min()
# find the global max
s['datemax'] = df['date'].max()
# combine two results 
s['date'] = [pd.date_range(x,y) for x,y in zip(s['date'],s['datemax'])]
out = s.explode('date').reset_index().merge(df,how='left').fillna(0)
out

    item shop       date    datemax   qty
0      1    A 2018-01-02 2018-01-05   5.0
1      1    A 2018-01-03 2018-01-05   6.0
2      1    A 2018-01-04 2018-01-05   0.0
3      1    A 2018-01-05 2018-01-05   0.0
4      1    B 2018-01-04 2018-01-05   9.0
5      1    B 2018-01-05 2018-01-05  10.0
6      2    A 2018-01-01 2018-01-05   7.0
7      2    A 2018-01-02 2018-01-05   0.0
8      2    A 2018-01-03 2018-01-05   0.0
9      2    A 2018-01-04 2018-01-05   8.0
10     2    A 2018-01-05 2018-01-05   0.0
,

我认为这给了你你想要的东西(列的顺序不同)

max_date = df.date.max()

def reindex_to_max_date(df):
    return df.set_index('date').reindex(pd.date_range(df.date.min(),max_date,name='date'),fill_value=0)

res = df.groupby(['shop','item']).apply(reindex_to_max_date)
res = res.qty.reset_index()

我按商店、商品分组以提供与 out 中相同的排序顺序,但这些可以互换。

,

不确定这是否是最有效的方法,但一个想法是创建一个包含所有日期的数据框,并在商店项目级别进行左连接,如下所示

初始数据

import pandas as pd


df = pd.DataFrame({'item': [1,1,2,1],'shop': ['A','A','B','B'],'date': pd.to_datetime(['2018.01.'+ str(x) 
                                           for x in [2,3,4,5]]),'qty': [5,6,7,8,9,10]})

df = df.set_index('date')\
       .groupby(['item','shop'])\
       .resample("D")['qty']\
       .sum()\
       .reset_index(name='qty')

包含所有日期的数据框

我们首先得到最大和最小日期

rg = df.agg({"date":{"min","max"}})

然后我们创建一个包含所有可能日期的 df

df_dates = pd.DataFrame(
    {"date": pd.date_range(
        start=rg["date"]["min"],end=rg["date"]["max"])
    })

完成日期

现在对于每个商店商品,我们都会对所有可能的日期进行左连接

def complete_dates(x,df_dates):
    item = x["item"].iloc[0]
    shop = x["shop"].iloc[0]
    x = pd.merge(df_dates,x,on=["date"],how="left")
    x["item"] = item
    x["shop"] = shop
    return x

我们最终将这个函数应用到原来的 df 上。

df.groupby(["item","shop"])\
  .apply(lambda x: 
         complete_dates(x,df_dates)
        )\
  .reset_index(drop=True)
         date  item shop   qty
0  2018-01-01     1    A   NaN
1  2018-01-02     1    A   5.0
2  2018-01-03     1    A   6.0
3  2018-01-04     1    A   NaN
4  2018-01-05     1    A   NaN
5  2018-01-01     1    B   NaN
6  2018-01-02     1    B   NaN
7  2018-01-03     1    B   NaN
8  2018-01-04     1    B   9.0
9  2018-01-05     1    B  10.0
10 2018-01-01     2    A   7.0
11 2018-01-02     2    A   0.0
12 2018-01-03     2    A   0.0
13 2018-01-04     2    A   8.0
14 2018-01-05     2    A   NaN
,

您可以使用 complete 中的 pyjanitor 函数来暴露缺失值;结束日期是 date 的最大值,每组 itemshop 的开始日期各不相同。

创建一个将目标列 date 与新日期范围配对的字典:

new_date = {"date" : lambda date: pd.date_range(date.min(),df['date'].max())}

new_date 变量传递给 complete :

# pip install https://github.com/pyjanitor-devs/pyjanitor.git
import janitor
import pandas as pd

df.complete([new_date],by = ['item','shop']).fillna(0)

    item shop       date   qty
0      1    A 2018-01-02   5.0
1      1    A 2018-01-03   6.0
2      1    A 2018-01-04   0.0
3      1    A 2018-01-05   0.0
4      1    B 2018-01-04   9.0
5      1    B 2018-01-05  10.0
6      2    A 2018-01-01   7.0
7      2    A 2018-01-02   0.0
8      2    A 2018-01-03   0.0
9      2    A 2018-01-04   8.0
10     2    A 2018-01-05   0.0

complete 只是 Pandas 函数的抽象,可以更轻松地显式暴露 Pandas 数据帧中的缺失值。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams['font.sans-serif'] = ['SimHei'] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -> systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping("/hires") public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate<String
使用vite构建项目报错 C:\Users\ychen\work>npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-
参考1 参考2 解决方案 # 点击安装源 协议选择 http:// 路径填写 mirrors.aliyun.com/centos/8.3.2011/BaseOS/x86_64/os URL类型 软件库URL 其他路径 # 版本 7 mirrors.aliyun.com/centos/7/os/x86
报错1 [root@slave1 data_mocker]# kafka-console-consumer.sh --bootstrap-server slave1:9092 --topic topic_db [2023-12-19 18:31:12,770] WARN [Consumer clie
错误1 # 重写数据 hive (edu)> insert overwrite table dwd_trade_cart_add_inc > select data.id, > data.user_id, > data.course_id, > date_format(
错误1 hive (edu)> insert into huanhuan values(1,'haoge'); Query ID = root_20240110071417_fe1517ad-3607-41f4-bdcf-d00b98ac443e Total jobs = 1
报错1:执行到如下就不执行了,没有显示Successfully registered new MBean. [root@slave1 bin]# /usr/local/software/flume-1.9.0/bin/flume-ng agent -n a1 -c /usr/local/softwa
虚拟及没有启动任何服务器查看jps会显示jps,如果没有显示任何东西 [root@slave2 ~]# jps 9647 Jps 解决方案 # 进入/tmp查看 [root@slave1 dfs]# cd /tmp [root@slave1 tmp]# ll 总用量 48 drwxr-xr-x. 2
报错1 hive> show databases; OK Failed with exception java.io.IOException:java.lang.RuntimeException: Error in configuring object Time taken: 0.474 se
报错1 [root@localhost ~]# vim -bash: vim: 未找到命令 安装vim yum -y install vim* # 查看是否安装成功 [root@hadoop01 hadoop]# rpm -qa |grep vim vim-X11-7.4.629-8.el7_9.x
修改hadoop配置 vi /usr/local/software/hadoop-2.9.2/etc/hadoop/yarn-site.xml # 添加如下 <configuration> <property> <name>yarn.nodemanager.res