gpt4 book ai didi

python - Pandas 时间序列和 groupby

转载 作者:行者123 更新时间:2023-12-01 05:29:47 32 4
gpt4 key购买 nike

[编辑以更清楚地说明根本问题,如果您使用 numpy 1.8,如 dmvianna 指出的那样,其行为会有所不同]

我有一个带有时间戳的 DataFrame 添加其他数据。最后,我不想使用格式化时间作为索引,因为它与 matplotlibs 3d 绘图混淆。我还想执行 groupby 来填充一些标志字段。这导致我遇到了许多奇怪的错误。前两个按我的预期工作。一旦我将 pd.to_datetime 放入图片中,它就会开始抛出错误。

按预期运行:

import pandas as pd
import numpy as np

df = pd.DataFrame({'time':np.random.randint(100000, size=1000),
'type':np.random.randint(10, size=1000),
'value':np.random.rand(1000)})

df['high'] = 0

def high_low(group):
if group.value.mean() > .5:
group.high = 1
return group

grouped = df.groupby('type')
df = grouped.apply(high_low)

工作正常:

df = pd.DataFrame({'time':np.random.randint(100000, size=1000),
'type':np.random.randint(10, size=1000),
'value':np.random.rand(1000)})

df.time = pd.to_datetime(df.time, unit='s')

df['high'] = 0

def high_low(group):
if group.value.mean() > .5:
group.high = 1
return group

grouped = df.groupby('type')
df = grouped.apply(high_low)

抛出错误:ValueError:传递值的形状为 (3, 1016),索引暗示 (3, 1000)

df = pd.DataFrame({'time':np.random.randint(100000, size=1000),
'type':np.random.randint(10, size=1000),
'value':np.random.rand(1000)})

df.time = pd.to_datetime(df.time, unit='s')
df = df.set_index('time')

df['high'] = 0

def high_low(group):
if group.value.mean() > .5:
group.high = 1
return group

grouped = df.groupby('type')
df = grouped.apply(high_low)

抛出错误:ValueError:传递值的形状为 (3, 1016),索引暗示 (3, 1000)

df = pd.DataFrame({'time':np.random.randint(100000, size=1000),
'type':np.random.randint(10, size=1000),
'value':np.random.rand(1000)})

df['epoch'] = df.time
df.time = pd.to_datetime(df.time, unit='s')
df = df.set_index('time')
df = df.set_index('epoch')

df['high'] = 0

def high_low(group):
if group.value.mean() > .5:
group.high = 1
return group

grouped = df.groupby('type')
df = grouped.apply(high_low)

有人知道我错过了什么/做错了什么吗?

最佳答案

我不会使用pd.to_datetime,而是使用np.datetime64。它将按列工作,并提供与 datetime.index 相同的功能(np.datetime64 是 datetime.index 的构建 block )。

import numpy as np
data['time2'] = np.datetime64(data.time, 's')

检查Docs

这也会导致相同的结果:

import pandas as pd
data['time2'] = pd.to_datetime(data.time, unit='s')

请注意,我使用的是 pandas 0.12.0 和 Numpy 1.8.0。 Numpy 1.7 存在以下评论中提到的问题。

关于python - Pandas 时间序列和 groupby,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20506531/

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