python - DataFrame.groupby.apply() 与 lambda 函数

标签 python pandas dataframe

我有一个数据框如下:

Datetime                 Value
--------------------------------------------
2000-01-01 15:00:00      10
2000-01-01 16:00:00      12
2000-01-01 17:00:00      14
2000-01-01 18:00:00      16
2000-01-02 15:00:00      13
2000-01-02 16:00:00      18
2000-01-02 17:00:00      16
2000-01-02 18:00:00      15
--------------------------------------------

我想得到一个列,我可以在其中获取从特定时间开始的每一天(比如 16:00:00)的值的差异,如下所示:

Datetime                 Value     NewColumn
--------------------------------------------
2000-01-01 15:00:00      10        -
2000-01-01 16:00:00      12        0
2000-01-01 17:00:00      14        2
2000-01-01 18:00:00      16        4
2000-01-02 15:00:00      13        -
2000-01-02 16:00:00      18        0
2000-01-02 17:00:00      16        -2
2000-01-02 18:00:00      15        -3
--------------------------------------------

我试过下面的代码,但它显示错误:

df['NewColumn'] = df.groupby('Datetime')['Value'].apply(lambda x: x - df.loc[(df['Datetime'].dt.time == dt.time(hour=16)), 'Value'])

ValueError: Buffer dtype mismatch, expected 'Python object' but got 'long long'

我应该如何编写代码?

最佳答案

IIUC,这就是你需要的。

df['Datetime']=pd.to_datetime(df['Datetime'])
df['NewColumn'] = (df.groupby(pd.Grouper(freq='D', key='Datetime'))['Value']
 .apply(lambda x: x - df.loc[x.loc[df['Datetime'].dt.hour == 16].index[0],'Value']))
df.loc[df['Datetime'].dt.hour < 16, 'NewColumn'] = '-'
print(df)

输出

              Datetime  Value   NewColumn
0   2000-01-01 15:00:00     10  -
1   2000-01-01 16:00:00     12  0
2   2000-01-01 17:00:00     14  2
3   2000-01-01 18:00:00     16  4
4   2000-01-02 15:00:00     13  -
5   2000-01-02 16:00:00     18  0
6   2000-01-02 17:00:00     16  -2
7   2000-01-02 18:00:00     15  -3

关于python - DataFrame.groupby.apply() 与 lambda 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58273919/

相关文章:

Python 日期时间解析时区(RFC3339)

python - 如何通过部分标签过滤pandas数据框列

r - 使用查找数据框以编程方式重命名数据框列

python - 转换数据框中(pandas/Python)中的系列,其中列是系列的级别

python - Pandas MultiIndex 的简单用例

python - 检查 python 日期列表中的任何日期是否在两个日期列之间

Scala:如何添加一个列,其中包含两个表之间更改的已更改字段的值

python - 子进程中的 sys.stdin.read() 永远不会返回

python - Pycrypto AES-CTR 实现

python - groupby 操作后按月对数据框进行排序