查找所有日期的通用ID python

时间:2019-04-24 13:22:23

标签: python pandas time-series

我在数据框中有两列。 ID和日期。我想找到所有给定日期通用的ID。有很多方法/解决方案可以解决此问题。我想知道python,pandas或numpy中是否有内置函数可以为我完成这项工作。让我通过示例向您展示:

  Date       Id
2019-04-01   334
2019-04-01   335
2019-04-01   336
2019-04-02   334
2019-04-02   335

在这种情况下的答案是:

  Date       Id
2019-04-01   334
2019-04-01   335
2019-04-02   334
2019-04-02   335

3 个答案:

答案 0 :(得分:2)

重塑并删除缺少值的列,因此每个组仅获取存在的值:

df = (df.groupby(['Date','Id'])
        .size()
        .unstack()
        .dropna(axis=1)
        .stack()
        .index
        .to_frame(index=False))
print (df)
         Date   Id
0  2019-04-01  334
1  2019-04-01  335
2  2019-04-02  334
3  2019-04-02  335

答案 1 :(得分:1)

这是transform + nunique

的一种方式
df[df.groupby(['Id'])['Date'].transform('nunique')==df.Date.nunique()]
Out[208]: 
         Date   Id
0  2019-04-01  334
1  2019-04-01  335
3  2019-04-02  334
4  2019-04-02  335

答案 2 :(得分:0)

您可以使用条件选择:

df.loc[df['column'] == value]

其中column是列的名称,而value是您要搜索的值。这将返回仅包含所选行的另一个数据框。您也可以使用同样的方法使用其他条件运算符,例如!=

相关问题