【发布时间】:2018-07-12 10:43:10
【问题描述】:
我有两个数据框:
df1 - 是一个数据透视表,包含列和行的总计,默认名称为“All” df2 - 我通过指定值并使用与上面数据透视表中使用的相同索引和列名手动创建的 df。此表没有总计。
我需要将第一个数据帧乘以第二个数据帧中的值。我希望总计返回 NaN,因为第二个表中不存在总计。
当我执行乘法时,出现以下错误:
ValueError: cannot join with no level specified and no overlapping names
当我在虚拟数据帧上尝试相同的操作时,它会按预期工作:
import pandas as pd
import numpy as np
table1 = np.matrix([[10, 20, 30, 60],
[50, 60, 70, 180],
[90, 10, 10, 110],
[150, 90, 110, 350]])
df1 = pd.DataFrame(data = table1, index = ['One','Two','Three', 'All'], columns =['A', 'B','C', 'All'] )
print(df1)
table2 = np.matrix([[1.0, 2.0, 3.0],
[5.0, 6.0, 7.0],
[2.0, 1.0, 5.0]])
df2 = pd.DataFrame(data = table2, index = ['One','Two','Three'], columns =['A', 'B','C'] )
print(df2)
df3 = df1*df2
print(df3)
这给了我以下输出:
A B C All
One 10 20 30 60
Two 50 60 70 180
Three 90 10 10 110
All 150 90 110 350
A B C
One 1.00 2.00 3.00
Two 5.00 6.00 7.00
Three 2.00 1.00 5.00
A All B C
All nan nan nan nan
One 10.00 nan 40.00 90.00
Three 180.00 nan 10.00 50.00
Two 250.00 nan 360.00 490.00
因此,从视觉上看,df1 和 df2 之间的唯一区别是“All”列和行的存在/不存在。
我认为我的虚拟数据帧和真实数据帧之间的唯一区别是真实的 df1 是使用 pd.pivot_table 方法创建的:
df1_real = pd.pivot_table(PY, values = ['Annual Pay'], index = ['PAR Rating'],
columns = ['CR Range'], aggfunc = [np.sum], margins = True)
当我在其他计算中使用它们时,我确实需要保留总数。
我确定有一种解决方法,但我真的很想了解为什么相同的代码适用于某些不同大小的数据帧,但不适用于其他数据帧。或者,问题可能是完全不同的东西。
感谢您的阅读。我意识到这是一个很长的帖子..
【问题讨论】:
标签: python pandas dataframe pivot-table multiplication