首页 > 解决方案 > Numpy,将数据帧乘以输出 NaN 的数字

问题描述

我正在尝试将数据框 1 列 a 乘以数据框 2 列 b。

combineQueryandBookFiltered['pnlValue'] = np.multiply(combineQueryandBookFiltered['pnlValue'], df_fxrate['fx_rate'])

pnlValue 列有很多数字,而 fx_rate 列只是一个数字。

代码执行,但我的最终结果是大量的NaN.

任何帮助,将不胜感激。

标签: pythonpython-3.xpandasnumpy

解决方案


这可能是由于您的数据框的索引。您需要使用 df_fxrate['fx_rate'].values

combineQueryandBookFiltered['pnlValue'] = np.multiply(combineQueryandBookFiltered['pnlValue'], df_fxrate['fx_rate'].values)

或更好:

combineQueryandBookFiltered['pnlValue']=combineQueryandBookFiltered['pnlValue']*df_fxrate['fx_rate'].values

我给你看一个例子:

df1=pd.DataFrame(index=[1, 2])
df2=pd.DataFrame(index=[0])
df1['col1']=[1,1]
print(df1)

 col1
1     1
2     1

df2['col1']=[1]
print(df2)

   col1
0     1

print(np.multiply(df1['col1'],df2['col1']))

0   NaN
1   NaN
2   NaN

如您所见,乘法是根据索引完成的

所以你需要这样的东西:

np.multiply(df1['col1'],df2['col1'].values)

或者

df1['col1']*df2['col1'].values

输出:

1    1
2    1
Name: 1, dtype: int64

如您所见,仅使用 df1['col1'] 系列索引


推荐阅读