python将根据日期列计算天数
我有一个数据框,有两列-‘路由名称’和‘日期’。路线名称包含各个城市的名称,“日期”表示这些城市记录的事件 例如,伦敦的过滤df如下=>python将根据日期列计算天数,python,pandas,Python,Pandas,我有一个数据框,有两列-‘路由名称’和‘日期’。路线名称包含各个城市的名称,“日期”表示这些城市记录的事件 例如,伦敦的过滤df如下=> Route Name Date London 2019-10-09 London 2019-10-09 London 2019-10-10 London 2019-10-10 London 2019-10-11 London 20
Route Name Date
London 2019-10-09
London 2019-10-09
London 2019-10-10
London 2019-10-10
London 2019-10-11
London 2019-10-11
London 2019-10-11
London 2019-10-11
London 2019-10-12
London 2019-10-12
London 2019-10-12
如何获得每个城市的天数?。预期的答案是
Route Name Frequency(days)
London 4
Manchester 5
Glasgow 5
等等。改编自广亨的评论,并修改为包括您关于每月计数的问题:
import pandas as pd
from io import StringIO
string = """Route Name\tDate
London\t2019-10-09
London\t2019-10-09
London\t2019-10-10
London\t2019-10-10
London\t2019-10-11
London\t2019-10-11
London\t2019-10-11
London\t2019-10-11
London\t2019-10-12
London\t2019-10-12
London\t2019-10-12
"""
df = pd.read_csv(StringIO(string), sep = "\t")
df["Date"] = pd.to_datetime(df["Date"], format = "%Y-%m-%d")
print(df.head())
"""
Route Name Date
0 London 2019-10-09
1 London 2019-10-09
2 London 2019-10-10
3 London 2019-10-10
4 London 2019-10-11
"""
df["Year"] = df["Date"].dt.year
df["Month"] = df["Date"].dt.month
print(df.head())
"""
Route Name Date Year Month
0 London 2019-10-09 2019 10
1 London 2019-10-09 2019 10
2 London 2019-10-10 2019 10
3 London 2019-10-10 2019 10
4 London 2019-10-11 2019 10
"""
annual_df = df.groupby(["Route Name", "Year"])["Date"].nunique()
print(annual_df.head())
"""
Route Name Year
London 2019 4
Name: Date, dtype: int64
"""
monthly_df = df.groupby(["Route Name", "Year", "Month"])["Date"].nunique()
print(monthly_df.head())
"""
Route Name Year Month
London 2019 10 4
Name: Date, dtype: int64
"""
df.groupby('Route Name').Date.nunique()。。这将给出总日期的计数。是否可以将其进一步分为两部分,以显示每月的计数?