Python 选择每个日期的最后时间戳

Python 选择每个日期的最后时间戳,python,pandas,multidimensional-array,Python,Pandas,Multidimensional Array,数据帧每天只包含几个时间戳,我需要为每个日期选择最新的时间戳(不是值,而是时间戳本身)。df如下所示: A B C 2016-12-05 12:00:00+00:00 126.0 15.0 38.54 2016-12-05 16:00:00+00:00 131.0 20.0 42.33 2016-12-14 05:00:00+00:00 129.0 18.0 43.24 2016-12-15

数据帧每天只包含几个时间戳,我需要为每个日期选择最新的时间戳(不是值,而是时间戳本身)。df如下所示:

                               A      B      C
2016-12-05 12:00:00+00:00  126.0   15.0  38.54
2016-12-05 16:00:00+00:00  131.0   20.0  42.33
2016-12-14 05:00:00+00:00  129.0   18.0  43.24
2016-12-15 03:00:00+00:00  117.0   22.0  33.70
2016-12-15 04:00:00+00:00  140.0   23.0  34.81
2016-12-16 03:00:00+00:00  120.0   21.0  32.24
2016-12-16 04:00:00+00:00  142.0   22.0  35.20
我通过定义以下功能实现了我所需要的:

def find_last_h(df,column):
    newindex = []
    df2 = df.resample('d').last().dropna()
    for x in df2[column].values:
        newindex.append(df[df[column]==x].index.values[0])
    return pd.DatetimeIndex(newindex)
使用它,我指定要用作过滤器的列的值,以获得所需的时间戳。这里的问题是在非唯一值的情况下,这可能无法按预期工作

使用的另一种方法是:

  grouped = df.groupby([df.index.day,df.index.hour])
  grouped.groupby(level=0).last()
然后重新构造时间戳,但它更为冗长。什么是聪明的方法?

与truncate
时代创建的掩码一起使用

idx = df.index.floor('D')
df = df[~idx.duplicated(keep='last') | ~idx.duplicated(keep=False)]
print (df)
                         A     B      C
2016-12-05 16:00:00  131.0  20.0  42.33
2016-12-14 05:00:00  129.0  18.0  43.24
2016-12-15 04:00:00  140.0  23.0  34.81
2016-12-16 04:00:00  142.0  22.0  35.20
另一个带+的解决方案:


重新采样
分组方式
日期
仅丢失时间:

print (df.resample('1D').last().dropna())
                A     B      C
2016-12-05  131.0  20.0  42.33
2016-12-14  129.0  18.0  43.24
2016-12-15  140.0  23.0  34.81
2016-12-16  142.0  22.0  35.20

print (df.groupby([df.index.date]).last())
                A     B      C
2016-12-05  131.0  20.0  42.33
2016-12-14  129.0  18.0  43.24
2016-12-15  140.0  23.0  34.81
2016-12-16  142.0  22.0  35.20
怎么样
df.resample('24H',kind='period').last().dropna()

你所说的损失时间是什么意思?输出只是没有时间的日期。检查我的答案并比较datetimeindex。我们可以通过kind='period',编辑答案,这样我可以得到正确的日期作为索引,但我们失去了原始时间(都是12:00),效果很好,谢谢!一个问题,是否真的需要|~idx.duplicated(keep=False)?我已经得到了正确的布尔数组,没有它!此代码获取所有唯一的行。也许你的真实数据中没有,但如果使用你的样本,3。没有它的行将被删除。这帮助我做了OP想要做的相反的事情(我需要做的),那就是删除每天的最后一个条目。只需要
df=df[idx.duplicated(keep='last')]
。这是否取决于原始数据帧的顺序?
print (df.resample('1D').last().dropna())
                A     B      C
2016-12-05  131.0  20.0  42.33
2016-12-14  129.0  18.0  43.24
2016-12-15  140.0  23.0  34.81
2016-12-16  142.0  22.0  35.20

print (df.groupby([df.index.date]).last())
                A     B      C
2016-12-05  131.0  20.0  42.33
2016-12-14  129.0  18.0  43.24
2016-12-15  140.0  23.0  34.81
2016-12-16  142.0  22.0  35.20