我正在尝试在groupby对象中执行动态转换。在这种情况下,我的分组是Account,每个帐户的Valuation列将减去Shift列中指定的行数。不久前有一个类似的问题,但涉及一个累加值,这里我只想知道值。请参见在数据帧上使用groupby进行动态移位。如果可能的话,由于性能原因,我想避免申请,因为我有数千万行。
import pandas as pd
import numpy as np
df = pd.DataFrame({
'Account': [1000001, 1000001, 1000001, 1000001, 1000001, 1000001, 1000001,
1000001, 1000001, 1000001, 1000002, 1000002, 1000002, 1000002,
1000002, 1000002, 1000002, 1000002, 1000002],
'Date': ['Jan-18', 'Feb-18', 'Mar-18', 'Apr-18', 'May-18', 'Jun-18',
'Jul-18', 'Aug-18', 'Sep-18', 'Oct-18', 'Jan-18', 'Feb-18',
'Mar-18', 'Apr-18', 'May-18', 'Jun-18', 'Jul-18', 'Aug-18',
'Sep-18'],
'Valuation':[ 50000, 51000, 52020, 53060, 54122, 55204, 56308, 57434,
58583, 59755, 100000, 102000, 104040, 106121, 108243, 110408,
112616, 114869, 117166],
'Shift': [3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2, 2, 2] })
所需的数据帧如下所示:
看一下这个。
def sh(x):
s = df.loc[x.index, 'Shift']
return (x.shift(-s.iloc[0]))
df['Valuation_shifted']= (df.groupby('Account')['Valuation'].apply(sh))
我知道您说过您不想申请。但是在这种情况下,我们不做lambda适用。而是,我们正在执行一个函数,该函数找出每个组中“ Shift”列的第一个值,并将“ Valuation_shifted”移位那么多。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句