python - Pandas 按具有重复日期时间的组重新采样

标签 python datetime pandas

这里有很多类似的问题,但我找不到任何实际具有相同日期时间的观察结果。一个最小的非工作示例是:

df = pd.DataFrame(
    {"Date": np.tile([pd.Series(["2016-01", "2016-03"])], 2)[0],
     "Group": [1,1,2,2],
     "Obs":[1,2,5,6]})

现在我想按组对 2016 年 2 月的值进行线性插值,因此所需的输出是

    Date    Group   Obs
    2016-01     1       1
    2016-02     1     1.5
    2016-03     1       2
    2016-01     2       5
    2016-02     2     5.5
    2016-03     2       6

我的理解是 resample 应该能够做到这一点(在我的实际应用程序中,我试图从每季度一次改为每月一次,因此在 1 月和 4 月进行了观察),但这需要一些某种时间索引,我不能这样做,因为 Date 列中有重复项。

我假设某种 groupby 魔术可以提供帮助,但无法弄清楚!

最佳答案

您可以使用:

#convert column Date to datetime
df['Date'] = pd.to_datetime(df.Date)
print (df)
        Date  Group  Obs
0 2016-01-01      1    1
1 2016-03-01      1    2
2 2016-01-01      2    5
3 2016-03-01      2    6

#groupby, resample and interpolate
df1 = df.groupby('Group').apply(lambda x : x.set_index('Date')
                                            .resample('M')
                                            .first()
                                            .interpolate())
                        .reset_index(level=0, drop=True).reset_index()

#convert Date to period
df1['Date'] = df1.Date.dt.to_period('M')
print (df1)
     Date  Group  Obs
0 2016-01    1.0  1.0
1 2016-02    1.0  1.5
2 2016-03    1.0  2.0
3 2016-01    2.0  5.0
4 2016-02    2.0  5.5
5 2016-03    2.0  6.0

编辑:

Pandas API 已更改 (0.18.1),因此现在您可以使用:

df['Date'] = pd.to_datetime(df.Date)
df.set_index('Date', inplace=True)

df1 = df.groupby('Group').apply(lambda df1: df1.resample('M')
                                               .first()
                                               .interpolate())
                         .reset_index(level=0, drop=True).reset_index()

df1['Date'] = df1.Date.dt.to_period('M')
print (df1)
     Date  Group  Obs
0 2016-01    1.0  1.0
1 2016-02    1.0  1.5
2 2016-03    1.0  2.0
3 2016-01    2.0  5.0
4 2016-02    2.0  5.5
5 2016-03    2.0  6.0

关于python - Pandas 按具有重复日期时间的组重新采样,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37296187/

相关文章:

python - 语法错误 : invalid syntax while building a dict from a list using Python 2. 6

Python any() 函数对于负数列表没有按预期运行

javascript - 如何从 JavaScript 中的 ISO 字符串获取时区名称?

python - 将嵌套字典中的键和值从列表格式获取到数据帧中

python - 为什么 df.apply(tuple) 有效但 df.apply(list) 无效?

python - 如何根据条件对数据框应用乘数?

python - 请求异常.MissingSchema : Invalid URL 'h' : No schema supplied

python - Django 保存随机行为

android - Joda-Time 返回错误的日期

c# - Azure 表存储错误地插入日期属性