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

时间:2019-06-25 11:56:32

标签: python pandas dataframe datetime iteration

我必须每月对一个数据框列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,请将Allocation除以11.116,而在2018-12中,将Allocation除以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'

我可以用这种方法解决问题还是应该使用其他方法?我很高兴有帮助

干杯!

1 个答案:

答案 0 :(得分:1)

也许您可以将列表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"]
相关问题