有没有办法使用 Python 检查某个值是否每周出现?

Is there a way to check if a certain value is appearing week on week using Python?

我有一个数据集,其中包含城市列表和每周的游客数量。我想做一些完整性检查,看看一个城市是否每周都出现。

图片显示了数据集的快照,但实际数据集有接近 1563 个城市:

[

我想检查 say Harare 是否在整个几周内始终如一地出现,所有其他城市(其中 1562 个城市)也是如此。

假设每个城市在给定日期可能只出现一次,一种选择是使用关系划分技术:

select city
from mytable
group by city
having count(*) = (select count(distinct week) from mytable)

这会为您提供所有日期出现的所有城市。

如果给定的城市在给定的日期可能出现不止一次,那么我们可以稍微更改一下 having 子句:

having count(distinct week) = (select count(distinct week) from mytable)

一个可能的解决方案是计算每个城市的周数并将计数与当前周数相匹配。

在 SQL 中,您可以执行类似

的操作
select 
   city, 
   count(week) over (partition by city) as appearance_num
from table_name

假设它存储在 Pandas Dataframe(名为 df)中:

no_of_weeks = len(set(df['Week']))
check = pd.DataFrame(df.groupby('City').Week.apply(lambda x: x.count() == no_of_weeks))
always_recorded = pd.DataFrame({'City': check.index.values, 'always_recorded': check['Week']})
always_recorded.index = [*range(1, len(always_recorded)+1)]
df2 = pd.merge(df, always_recorded, how = "left", on = "City")
subset = df2[df2.always_recorded == True]