python - 仅显示 pandas 中日期范围行的交集

标签 python pandas dataframe pandas-groupby

here之后

import pandas as pd

data = {'date': ['1998-03-01 00:00:01', '2001-04-01 00:00:01','1998-06-01 00:00:01','2001-08-01 00:00:01','2001-05-03 00:00:01','1994-03-01 00:00:01'], 
        'node1': [1, 1, 2,2,3,2],
     'node2': [8,316,26,35,44,56],
     'weight': [1,1,1,1,1,1], }
df = pd.DataFrame(data, columns = ['date', 'node1','node2','weight'])

df['date'] = pd.to_datetime(df['date'])

mask = df.groupby('node1').apply(lambda x : (x['date'].dt.year.isin([1998,1999,2000])).any())
mask2 = df.groupby('node1').apply(lambda x : (x['date'].dt.year.isin([2001,2002,2003])).any())


print df[df['node1'].isin(mask[mask & mask2].index)]

我需要的输出是年份范围 (98-00) 和 (01-03) 中的节点,但它也应该只显示这两个范围中的行。

预期输出-

node1          node2         date
1                8          1998-03-01
1               316         2001-04-01
2               26          1998-06-01
2              35           2001-08-01  

现在这段代码也打印了这一行:2 56 1994-03-01。

最佳答案

一个简单的解决方案是首先删除不在两个日期范围内的日期,然后应用掩码,即

l1 = [1998,1999,2000]
l2 = [2001,2002,2003]
ndf = df[df['date'].dt.year.isin(l1+l2)]

获取ndf后:

选项 1:您可以采用基于双 groupby 掩码的方法,即

mask = ndf.groupby('node1').apply(lambda x : (x['date'].dt.year.isin(l1)).any())
mask2 = ndf.groupby('node1').apply(lambda x : (x['date'].dt.year.isin(l2)).any())

new =  ndf[ndf['node1'].isin(mask[mask & mask2].index)]

谢谢@零

选项 2:您可以进行 groupby 转换

new = ndf[ndf.groupby('node1')['date'].transform(lambda x: x.dt.year.isin(l1).any() & x.dt.year.isin(l2).any())]

选项 3: groupby 过滤器

new = ndf.groupby('node1').filter(lambda x: x['date'].dt.year.isin(l1).any() & x['date'].dt.year.isin(l2).any())

输出:

                 date  node1  node2  weight
0 1998-03-01 00:00:01      1      8       1
1 2001-04-01 00:00:01      1    316       1
2 1998-06-01 00:00:01      2     26       1
3 2001-08-01 00:00:01      2     35       1

关于python - 仅显示 pandas 中日期范围行的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500619/

相关文章:

python - 使用外键为字段赋值

python - 加载 spacy 时出错 - 'en_core_web_sm' 库

python - 我们如何在 python 中的重复非数字列值之间绘制包含两列以上信息的折线图?

Python 一般数字格式化行为

Python 在 s 中切片 'bob'

python - 如何转发/填充 Pandas DataFrame 列/系列中的特定值?

python - 使用python和pandas制作MIS折线图

python - 如何将数据保存到 csv Cantera 和错误 <cantera.composite.SolutionArray object at 0x7f4badca0fd0>

pandas - 推断数据框行

python - 用 pandas 数据框中的一些默认值填充每个列组合的值