来自两个系列的笛卡尔积,长度和索引不同 [英] Cartesian product from two Series, different lengths and indexes

查看:32
本文介绍了来自两个系列的笛卡尔积,长度和索引不同的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出两个系列:

import pandas as pd
ser1 = pd.Series(data = [1,2,3], index=[1,2,3])
ser2 = pd.Series(data = [1,2,3,4,5], index = ['a','b','c','d','e'])

如何将两者相乘以获得所需的输出?

How can I cross-multiply the two to get this desired output?

pd.DataFrame(
data = [[1,2,3],[2,4,6],[3,6,9],[4,8,12],[5,10,15]],
index = ser2.index,
columns = ser1.index,)

到目前为止,我的方法是使用索引和cols匹配两个系列的临时数据帧,然后使用iteritems()遍历两个系列之一.我觉得应该有一种更清洁的方法来实现这一目标.

My approach so far has been to build a temporary dataframe with index and cols matching the two series, and then iterate over one of the two series using iteritems(). I feel like there should be a cleaner way to achieve this.

推荐答案

我认为需要 numpy.outer 表示两个Series的外部乘积:

I think need numpy.outer for outer product of two Series:

df = pd.DataFrame(np.outer(ser2, ser1), index = ser2.index, columns = ser1.index)

print (df)
   1   2   3
a  1   2   3
b  2   4   6
c  3   6   9
d  4   8  12
e  5  10  15

这篇关于来自两个系列的笛卡尔积,长度和索引不同的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆