python - 将df中的许多列减去另一df中的一列

标签 python pandas

我正在尝试用df“p_df”(144行x 1列)减去df“stock_returns”(144行x 517列)。

我试过了;

stock_returns - p_df

stock_returns.rsub(p_df,axis=1)
stock_returns.substract(p_df)

但是它们都不起作用,并且都返回Nan值。

我正在通过此fnc传递它,并使用for循环来获取args:
def disp_calc(returns, p, wi):    #apply(disp_calc, rows = ...)
    wi = wi/np.sum(wi)
    rp = (col_len(returns)*(returns-p)**2).sum()      #returns - p causing problems    
    return np.sqrt(rp)

for i in sectors:
    stock_returns = returns_rolling[sectordict[i]]#.apply(np.mean,axis=1)          
    portfolio_return = returns_rolling[i]; p_df = portfolio_return.to_frame()
    disp_df[i] = stock_returns.apply(disp_calc,args=(portfolio_return,wi))

我的预期输出是将第一个df中的所有517个cols减去p_df中的1个col。因此最终结果仍为517列。谢谢

最佳答案

您快到了,只需要设置axis=0即可沿索引减去:

>>> stock_returns = pd.DataFrame([[10,100,200], 
                             [15, 115, 215], 
                             [20,120, 220], 
                             [25,125,225], 
                             [30,130,230]], columns=['A', 'B', 'C']) 
>>> stock_returns

   A    B    C
0  10  100  200
1  15  115  215
2  20  120  220
3  25  125  225
4  30  130  230

>>> p_df = pd.DataFrame([1,2,3,4,5], columns=['P'])
>>> p_df

   P
0  1
1  2
2  3
3  4
4  5

>>> stock_returns.sub(p_df['P'], axis=0)

    A    B    C
0   9   99  199
1  13  113  213
2  17  117  217
3  21  121  221
4  25  125  225

关于python - 将df中的许多列减去另一df中的一列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45383144/

相关文章:

python - 如何使用列表值对字典进行排序?

python - 将 pandas 数据框转换为定向 networkx 多图

python - Pandas:查找一列中相隔 50 个单位的连续项目

python - pandas 中的 Groupby 返回太多行

python - Selenium Python 使用键盘快捷键打开群组中的所有 Facebook 帖子

python - 以右对齐的精度打印 float

python - 使用Pandas dataframe处理列表数据get loc错误

python - 没有表单的 Django 用户创建

python-2.7 - 如何将对列表(到矩阵)转换为热图; Python

python - 如何使用 Pandas 将数据库表中的 nan 转换为 NULL