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