通过将A.column2中的值与另一个数据帧B

时间:2016-10-09 16:05:22

标签: python pandas join dataframe

我有两个数据帧(df)A和B. df A有一个名为'符号'将非独特的股票 - 股票代码 - 符号作为随机顺序的值以及另一列中相应的买入或卖出数量的数量称为“股票”;它由非负整数索引。 df B,以与df A相同的日期顺序的日期索引,与df A的行数相同,具有与df A相同的股票代码作为唯一列名。我需要使用相应A.Shares.values的股票购买或卖出金额填充所有df B行。尝试以下代码时出错。或者,是否可以使用join命令约束遍历df A行,以将df A的列值与df B的列名匹配,类似于SQL查询?

import pandas as pd

bCN = B.dtypes.index # list of column names in df B to be used for populating its stock quantity based on matching values from df A

A = pd.DataFrame({'Date': ['2011-01-14', '2011-01-19', '2011-01-19'], 'Symbol': ['AAPL', 'AAPL', 'IBM'], 'Order':['BUY','SELL','BUY'],'Shares':[1500, 1500, 4000]}) #example of A

B = pd.DataFrame({'AAPL':[0,0,0],'IBM': [0,0,0], index = pd.date_range(start, end)}) #example of B

预期结果

B = pd.DataFrame({'AAPL':[1500,0,-1500],'IBM': [0,0,400], index = pd.date_range(start, end)}) #example of resultant B

尝试

    B = A.pivot('Date','Symbol','Shares')
    B = B.fillna(value = 0)
    B['Cash'] = pd.Series([0]*len(B.index),index=B.index)
    for index, row in A.iterrows():    
        if row['Order'] == 'SELL':
            B.loc[row, A['Symbol']] *= -1 

1 个答案:

答案 0 :(得分:0)

首先,我强烈建议您阅读how-to-make-good-reproducible-pandas-examples

我认为您可以使用枢轴,例如:

B = A.pivot('Date','Symbol','Shares')

由于数据帧的图像难以复制粘贴,因此我无法向您展示使用此方法可获得的确切结果

相关问题