TownA = [35, 43, 36, 39, 28, 28, 29, 25, 38, 27, 26, 32, 29, 40, 35, 41, 37, 31, 45, 34]
TownB = [27, 15, 4, 41, 49, 25, 10, 30]
Rural = [8, 14, 12, 15, 30, 32, 21, 20, 34, 7, 11, 24]
tv_viewing = TownA + TownB + Rural
labels = np.array(["TownA", "TownB", "Rural"])
stratum = np.repeat(labels, [len(TownA), len(TownB), len(Rural)], axis=0)
sample = pd.DataFrame()
sample["viewership"] = tv_viewing
sample["stratum"] = stratum
sample.groupby("stratum").mean()
上面的代码生成了一个如下所示的数据框:
我的目标是将这个数据框与下面的字典相乘:
Population = {"TownA": 155, "TownB": 62, "Rural": 93}
为了获得想要的结果:
我不挑剔最终结果,产品可以是一个新的专栏。
我能够通过以下代码获得解决方案:
a = sample.groupby("stratum").mean().reset_index()
b = pd.DataFrame.from_dict(N, orient='index').reset_index()
ab = pd.merge(a, b, left_on='stratum', right_on='index')
ab["product"] = ab["viewership"]*ab[0]
代码生成此表:
我想知道是否有更优雅的方法来解决这个问题而无需重置索引并使用诸如应用之类的东西。
我试过这段代码:
a = sample.groupby("stratum").mean().apply(lambda x: x.viewership * N[x.stratum])
只是为了得到这个错误: “系列”对象没有属性“收视率”
最佳答案
在轴 = 0 时使用 mul
方法:
out = sample.groupby("stratum").mean()
out.mul(Population, axis = 0 )
viewership
stratum
Rural 1767.00
TownA 5254.50
TownB 1557.75
关于python - 将 Pandas 数据框乘以字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72737721/