如何基于整数索引和熊猫中的另一个列值返回一个列值?

时间:2018-11-26 12:44:32

标签: pandas function apply

我有一个df,我想对Date进行分组并对其应用一个函数。

          Date      Symbol    Shares 
0   1990-01-01      A         0.0        
1   1990-01-01      B         0.0        
2   1990-01-01      C         0.0         
3   1990-01-01      D         0.0  
4   1990-01-02      A         50.0     
5   1990-01-02      B         100.0      
6   1990-01-02      C         66.0      
7   1990-01-02      D         7.0       
8   1990-01-03      A         11.0      
9   1990-01-03      B         123.0      
10  1990-01-03      C         11.0      
11  1990-01-03      D         11.0      

我应该能够从函数中的前一个Shares访问Symbol的{​​{1}}值。我怎样才能做到这一点?在应用函数之前像Date一样创建df[prev_shares]是不可选项,因为函数会逐行计算df.groupby('Symbol')['Shares'].shift(1)
它应该看起来像:

Shares

任何帮助表示赞赏。

编辑:

我发布了我创建的函数。

def calcs(x):
    x.loc[some_condition, 'Shares'] = ...
    x.loc[other_condition, 'Shares'] = # return 'Shares' from previous 'Date' for this 'Symbol'

df = df.groupby('Date').apply(calcs)

1 个答案:

答案 0 :(得分:0)

IIUC这样的事情可能会有所帮助,尽管您最终要完成的工作尚不清楚。您将在下面找到按“符号”和“日期”分组的数据。 “ diff”列显示了增量P / L。

请另外告知您需要什么。

df =  data.set_index(['Symbol', 'Date']).sort_index()[['Shares']]
df['diff'] = np.nan
idx = pd.IndexSlice

for ix in df.index.levels[0]:
    df.loc[ idx[ix,:], 'diff'] = df.loc[idx[ix,:], 'Shares' ].diff()

df.fillna(0)

                   Shares   diff
Symbol Date                     
A      1990-01-01     0.0    0.0
       1990-01-02    50.0   50.0
       1990-01-03    11.0  -39.0
B      1990-01-01     0.0    0.0
       1990-01-02   100.0  100.0
       1990-01-03   123.0   23.0
C      1990-01-01     0.0    0.0
       1990-01-02    66.0   66.0
       1990-01-03    11.0  -55.0
D      1990-01-01     0.0    0.0
       1990-01-02     7.0    7.0
       1990-01-03    11.0    4.0