【问题标题】:Drop empty time based groups in pandas在 pandas 中删除基于空时间的组
【发布时间】:2018-01-19 12:50:54
【问题描述】:

我使用 group by 将数据框分组为不同的日期,然后使用 concat 根据日期将它们分成训练组和测试组

gp = dfs_0.groupby(pd.TimeGrouper('B'))

train = pd.concat([ gp.get_group(group) for i,group in enumerate( gp.groups) if i < len(gp)-1 ])
test = pd.concat([ gp.get_group(group) for i,group in enumerate( gp.groups) if i == len(gp)-1 ])

但是,如果工作日是银行保留,我没有数据,因此返回错误的空组:

Traceback(最近一次调用最后一次):文件“”,第 1 行,in 文件“”,第 1 行,在文件中 "C:\ProgramData\Anaconda3\lib\site-packages\pandas\core\groupby.py", 第 640 行,在 get_group 中 raise KeyError(name) KeyError: Timestamp('2014-04-18 00:00:00', freq='B')

有没有办法在连接前过滤掉这些空组

【问题讨论】:

  • 你能添加一些数据样本吗?
  • 我尝试测试您的解决方案,len(gp)-1 始终返回标量 - 没有 1 的所有组的大小。可以吗?
  • 是的,这绝对没问题。我这样做有基于技术模型的原因
  • jezrael 我会通过电子邮件向您发送一些数据
  • 超级,最好的一些返回问题的数据

标签: python pandas


【解决方案1】:

有问题有些没有Dates,所以得到KeyError

我尝试创建自定义函数:

rng = pd.to_datetime(['2014-04-16','2014-04-17','2014-04-22 00:11:00','2014-04-22',
                      '2014-04-23','2014-04-23 10:00:03','2014-04-23 14:01:08'])
dfs_0 = pd.DataFrame({'col': range(7)}, index=rng)  
print (dfs_0)
                     col
2014-04-16 00:00:00    0
2014-04-17 00:00:00    1
2014-04-22 00:11:00    2
2014-04-22 00:00:00    3
2014-04-23 00:00:00    4
2014-04-23 10:00:03    5
2014-04-23 14:01:08    6

gp = dfs_0.groupby(pd.TimeGrouper('B'))

def get_cust_group(g, key):
    try:
        return g.get_group(key)
    except KeyError:
        return pd.DataFrame()

#change to get_cust_group
train = pd.concat([ get_cust_group(gp,group) for i,group in enumerate( gp.groups) if i < len(gp)-1 ])
test = pd.concat([ get_cust_group(gp,group) for i,group in enumerate( gp.groups) if i == len(gp)-1 ])
print (train)
                     col
2014-04-16 00:00:00    0
2014-04-17 00:00:00    1
2014-04-22 00:00:00    3
2014-04-22 00:11:00    2

print (test)
                     col
2014-04-23 00:00:00    4
2014-04-23 10:00:03    5
2014-04-23 14:01:08    6

【讨论】:

  • 我不知道如何使这个建议发挥作用。
  • 真实数据中的某些值是否可能是 NaN?
  • 2014-04-17 11:59:58.465212000,5,0.009012476282633809 2014-04-22 08:00:00.207384400,-5,0.016332909547638837
  • 当我使用 groupby 时,使用“B”工作日会增加 18 日
  • gp = dfs_0.groupby([dfs_0.index.year, dfs_0.index.month, dfs_0.index.day]) 这是最好的选择
猜你喜欢
  • 2016-09-05
  • 1970-01-01
  • 2022-07-02
  • 1970-01-01
  • 2022-08-18
  • 1970-01-01
  • 2020-11-26
  • 1970-01-01
  • 2014-09-07
相关资源
最近更新 更多