Python 使用pandas,如何重新采样并应用函数来添加列?

Python 使用pandas,如何重新采样并应用函数来添加列?,python,pandas,Python,Pandas,我对熊猫是完全陌生的,正在做我的第一步。我被卡住了,即使研究没有带来任何结果,很可能我没有使用正确的术语 我有以下表格中的初始数据 datetime counter 2019-06-01 17:57:54 159411631 2019-06-01 17:57:54 159411642 2019-06-01 17:57:54 159411642 2019-06-01 17:58:03 159411642 2019-06-01 17:58:03 15941164

我对熊猫是完全陌生的,正在做我的第一步。我被卡住了,即使研究没有带来任何结果,很可能我没有使用正确的术语

我有以下表格中的初始数据

           datetime    counter
2019-06-01 17:57:54  159411631
2019-06-01 17:57:54  159411642
2019-06-01 17:57:54  159411642
2019-06-01 17:58:03  159411642
2019-06-01 17:58:03  159411643
这表示直接从计数器读取的耗电量的累计总值

我现在想根据这些数据计算每天的消费量

我正在尝试按日期重新采样数据:

res = df.resample('D').max() - df.resample('D').min()
这不起作用,因为熊猫不知道如何减去日期列。我不知道如何只选择一列。。。我不确定明确选择一列是否是熊猫式的做法

从上述数据中获取每日消费量的正确方法是什么

      date  consumption
2019-06-01         3968 
2019-06-02         9491
2019-06-03        20444
使用上的参数
并将其添加到
重采样

df['datetime'] = pd.to_datetime(df['datetime'])
res = (df.resample('D', on='datetime')['counter'].max() - 
       df.resample('D', on='datetime')['counter'].min())
或创建
DatetimeIndex

df['datetime'] = pd.to_datetime(df['datetime'])
df = df.set_index('datetime')
res = (df.resample('D').max() - 
       df.resample('D').min()).reset_index().rename(columns={'counter':'consumption'})

最后将
系列
转换为
数据帧

res = res.reset_index(name='consumption')
print (res)
    datetime  consumption
0 2019-06-01           12
res = res.reset_index(name='consumption')
print (res)
    datetime  consumption
0 2019-06-01           12