Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/performance/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 用一个列快速乘以一个年系数_Python_Performance_Pandas_Multiplication - Fatal编程技术网

Python 用一个列快速乘以一个年系数

Python 用一个列快速乘以一个年系数,python,performance,pandas,multiplication,Python,Performance,Pandas,Multiplication,我有一个带有日期时间索引的数据框: df = pd.DataFrame( {'test':[1, 1, 1, 1, 1, 1]}, index=[ '2018-01-01', '2018-01-02', '2018-01-03', '2019-01-03', '2019-01-02', '2020-01-02' ] ) df.index= pd.to_datetime(df.index) 我有一个参数: yearly_paramete

我有一个带有日期时间索引的数据框:

df = pd.DataFrame(
    {'test':[1, 1, 1, 1, 1, 1]},
    index=[
        '2018-01-01', '2018-01-02', '2018-01-03',
        '2019-01-03', '2019-01-02', '2020-01-02'
    ]
 )
df.index=  pd.to_datetime(df.index)
我有一个参数:

yearly_parameter = [1, 2, 3]
我想(以矢量化的方式?)将列“test”高效地乘以列表年度参数中包含的相应年度参数(第一个值用于2018年,第二个值用于2019年,第三个值用于2020年)。我怎样才能有效地做到这一点?列表是存储这些年度参数进行计算的好方法吗

我希望在一列中显示以下结果,比如“答案”:

df['answer'] = [1, 1, 1, 2, 2, 3]

print(df)

              test  answer
2018-01-01     1       1
2018-01-02     1       1
2018-01-03     1       1
2019-01-03     1       2
2019-01-02     1       2
2020-01-02     1       3
非常感谢您的帮助

皮埃尔

使用
factorize
建立年序,该年序应与
yearly\u参数中的元素相对应。然后我们可以有效地使用数组切片进行乘法

这要求
year_参数的长度至少与
df.index

f, y = pd.factorize(df.index.year)

yearly_parameter = np.array([1, 2, 3])

df.assign(answer=df.test.values * yearly_parameter[f])

            test  answer
2018-01-01     1       1
2018-01-02     1       1
2018-01-03     1       1
2019-01-03     1       2
2019-01-02     1       2
2020-01-02     1       3

请注意,这假定
yearly_参数
将其第一个元素与观察到的第一年对齐。如果您希望第一个元素对应于观察到的最小年份,则应使用
pd.factorize(df.index.year,sort=True)
。或者更好的方法是,如果要排序,则使用Numpy中的等效计算

y, f = np.unique(df.index.year, return_inverse=True)

yearly_parameter = np.array([1, 2, 3])

df.assign(answer=df.test.values * yearly_parameter[f])

            test  answer
2018-01-01     1       1
2018-01-02     1       1
2018-01-03     1       1
2019-01-03     1       2
2019-01-02     1       2
2020-01-02     1       3