python - 在数据框 Pandas 中选择日期范围

标签 python datetime pandas dataframe slice

首先非常感谢那些提供帮助的人,当人们提供帮助时,学习很有趣。

我没有切片和向下选择,我有一个数据框

             Unit   Name          Count   Month Year
2013-01-01   U1     fn ln         2       01    2013
2013-01-01   U1     fn1 ln1       200     01    2013
2013-02-01   U2     fn2 ln2       55      01    2013
...
2016-01-01   U1     fn3 ln3       2       01    2016
2016-01-01   U1     fn1 ln1       200     01    2016
2016-01-01   U2     fn5 ln5       55      01    2016

我想创建此数据的各种切片。

首先是每个月的总体,其次是每个单位每月的总体,然后是本月、过去三个月和过去 6 个月的个人

到目前为止的代码

# this works great groups by year per month (1 2013, 2014, 2015)...
group1=df.groupby('Month','Year')

# works great to select by unit
group2=df.groupby('Unit', 'Month', 'Year')

# now i want the top 10 individuals in each group
# this doesn't work
month_indiv = group2[['Name', 'Count']]

我认为问题是 groupby 删除了重复项,但我不明白如何创建给我个人的 View 。

最佳答案

您可以通过 to_period 将索引转换为 periodindex并找到最近 3 个月的 unique :

print df
           Unit     Name  Count  Month  Year
2013-01-01   U1    fn ln      2      1  2013
2013-02-01   U1    fn ln      2      2  2013
2013-02-01   U1  fn1 ln1    200      2  2013
2013-03-01   U2  fn2 ln2     55      3  2013
2013-04-01   U2  fn2 ln2     55      4  2013
2013-05-01   U2  fn2 ln2     55      5  2013
2016-01-01   U1  fn3 ln3      2      1  2016
2016-01-01   U1  fn1 ln1    200      1  2016
2016-01-01   U2  fn5 ln5     55      1  2016

#convert index to Periodindex
print df.index.to_period('M')
PeriodIndex(['2013-01', '2013-02', '2013-02', '2013-03', '2013-04', '2013-05',
             '2016-01', '2016-01', '2016-01'],
            dtype='int64', freq='M')

#last 3 unique values
print df.index.to_period('M').unique()[-3:]
PeriodIndex(['2013-04', '2013-05', '2016-01'], dtype='int64', freq='M')

print df.index.to_period('M').isin(df.index.to_period('M').unique()[-3:])
[False False False False  True  True  True  True  True]

#last 3 months
print  df.loc[df.index.to_period('M').isin(df.index.to_period('M').unique()[-3:])]
           Unit     Name  Count  Month  Year
2013-04-01   U2  fn2 ln2     55      4  2013
2013-05-01   U2  fn2 ln2     55      5  2013
2016-01-01   U1  fn3 ln3      2      1  2016
2016-01-01   U1  fn1 ln1    200      1  2016
2016-01-01   U2  fn5 ln5     55      1  2016

关于python - 在数据框 Pandas 中选择日期范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35111235/

相关文章:

php - 如何在 PHP 中将日期时间转换为 ISO 8601

java - JodaTime 比较两个不同时区的日期

Pandas 选择匹配多列

python - 添加超范围;如何?

python - 合并不同范围的直方图

python - 无法使用 python 中的套接字模块远程登录到 Windows

python - 从 Pandas 日期时间列中分别提取月份和年份

python - 如何用 Pandas 对象中的子字符串替换值?

python - Pymssql,如何使用它从 MSSQL2008 中读取 unicode 数据

javascript - 在 Django 中做 ajax 的更好方法