gpt4 book ai didi

python - 放 Pandas 数据框时,不要填写超出每一行的时间段

转载 作者:太空宇宙 更新时间:2023-11-04 09:30:53 25 4
gpt4 key购买 nike

在使用 Pythonpandas 库放大数据帧时,我遇到了意外行为。

例子

让我们从每月数据开始:

carMonthly = pd.DataFrame(data={'avSpeed': [40.3, 23.4], 'dist': [100, 150]},
index=pd.PeriodIndex(['2019-02', '2019-05'], freq='M'))

avSpeed dist
2019-02 40.3 100
2019-05 23.4 150

请注意我如何使用每月频率的 PeriodIndex

想要的结果

现在,我想通过以下方式将此集合重新调整为每日值:

  • 必须将 avSpeed 值复制到该特定月份的每一天;
  • dist 值必须除以每个月的天数(第一行 28 天,第二行 31 天)。

所以,我希望的结果是:

            avSpeed      dist
2019-02-01 40.3 3.571428
2019-02-02 40.3 3.571428
...
2019-02-27 40.3 3.571428
2019-02-28 40.3 3.571428 #until end of February
2019-05-01 23.4 4.838710
2019-05-02 23.4 4.838710
...
2019-05-30 23.4 4.838710
2019-05-31 23.4 4.838710

请注意 March 和 April 是如何不存在的。如果那不可能,并且生成的重采样将始终包括三月和四月,我的第二好的结果是那些月份的所有行都包含 NaN 值。

什么不起作用

对于那些对我的尝试感兴趣的人:

carDaily = pd.DataFrame()
carDaily['avSpeed'] = carMonthly['avSpeed'].resample('D').ffill()
tempSeries = carMonthly['dist'].resample('D').first()
carDaily['dist'] = tempSeries.groupby(tempSeries.notna().cumsum())\
.apply(lambda x: x/len(x.index)).ffill()

avSpeed dist
2019-02-01 40.3 1.123596
2019-02-02 40.3 1.123596
...
2019-04-29 40.3 1.123596
2019-04-30 40.3 1.123596 #until end of April
2019-05-01 23.4 4.838710
2019-05-02 23.4 4.838710
...
2019-05-30 23.4 4.838710
2019-05-31 23.4 4.838710

这是不需要的,因为2 月份的数据一直延伸到 4 月底。因为原始数据集有每月一次的频率,而 carMonthly 数据集中的每一行都涵盖了一个月的时间段,所以我想要复制(avSpeed)或除以( dist) 限制在 carDaily 数据集中实际位于其数据来自的月份内的那些行,如“首选结果”下所示。

我知道它为什么不起作用:重采样的 Series 对所有行(包括三月和四月)都有 NaN 值,2019-02-01 除外2019-05-01,那时无法找出原始的 start_timeend_time几个月是。我只是不知道,如何让它工作:)

PS:dist列的解决方案取自this问题。


编辑:解决方案

this在下面回答,我现在正在使用这段代码,它允许我逐列构建新的数据框:

tempDf = carMonthly.groupby(level=0).apply(lambda x : x.resample('D').ffill())
il = tempDf.index.labels[0]
divBy = [sum(il==i) for i in il]

carDaily = pd.DataFrame()
carDaily['avSpeed'] = tempDf['avSpeed']
carDaily['dist'] = tempDf['dist'] / divBy
carDaily.reset_index(level=0,drop=True,inplace=True)
  • 我喜欢这个解决方案的一点是,我只需要计算一次 divBy 列表 (il = FrozenNDArray([0, 0, 0, 0, 0, 0, 0 , 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1 , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 , 1, 1], dtype='int8')).
  • 如果我将采样时间从几个月提高到几小时,或者从几年提高到几个月,它仍然有效。
  • 仅依赖于 pandas 作为外部库。

最佳答案

你应该在 groupbyresample

s=carMonthly.groupby(level=0).apply(lambda x : x.resample('D').ffill())
s['dist']/=s.groupby(level=0)['avSpeed'].transform('count').values
s.reset_index(level=0,drop=True,inplace=True)

关于python - 放 Pandas 数据框时,不要填写超出每一行的时间段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55834815/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com