根据索引值对数据帧列执行计算

2024-04-28 23:49:03 发布

您现在位置:Python中文网/ 问答频道 /正文

我必须每月规范化一个数据帧列Allocation的值

data=
                     Allocation  Temperature  Precipitation  Radiation
Date_From                                                             
2018-11-01 00:00:00    0.001905         9.55            0.0        0.0
2018-11-01 00:15:00    0.001794         9.55            0.0        0.0
2018-11-01 00:30:00    0.001700         9.55            0.0        0.0
2018-11-01 00:45:00    0.001607         9.55            0.0        0.0

这意味着,如果我们有2018-11年,除以11.116,而在2018-12年,除以2473.65,依此类推(这些值来自一个列表Volume,其中Volume[0]对应于2018-11直到Volume[7]对应于2019-06)

Date_From是索引和时间戳

data_normalized=
                     Allocation  Temperature  Precipitation  Radiation
Date_From                                                             
2018-11-01 00:00:00    0.000171         9.55            0.0        0.0
2018-11-01 00:15:00    0.000097         9.55            0.0        0.0
...

我的方法是使用itertuples:

for row in data.itertuples(index=True,name='index'):
    if row.index =='2018-11':
        data['Allocation']/Volume[0]

在这里,if语句从来都不是真的

另一种方法是 if ((row.index >='2018-11-01 00:00:00') & (row.index<='2018-11-31 23:45:00')): 但是,这里有一个错误TypeError: '>=' not supported between instances of 'builtin_function_or_method' and 'str'

我能用这种方法解决我的问题吗?还是应该用另一种方法?我很高兴能得到任何帮助

干杯


Tags: 数据方法fromdatadateindexif规范化
1条回答
网友
1楼 · 发布于 2024-04-28 23:49:03

也许您可以将您的列表Volume放在一个数据框中,其中日期(或索引)是每个月的第一天

import pandas as pd
import numpy as np

N = 16
date = pd.date_range(start='2018-01-01', periods=N, freq="15d")
df = pd.DataFrame({"date":date, "Allocation":np.random.randn(N)})

# A dataframe where at every month associate a volume
df_vol = pd.DataFrame({"month":pd.date_range(start="2018-01-01", periods=8, freq="MS"),
                       "Volume": np.arange(8)+1})

# convert every date with the beginning of the month
df["month"] = df["date"].astype("datetime64[M]")

# merge
df1 = pd.merge(df,df_vol, on="month", how="left")

# divide allocation by Volume. 
# Now it's vectorial as to every date we merged the right volume.
df1["norm"] = df1["Allocation"]/df1["Volume"]

相关问题 更多 >