首页 > 解决方案 > 不同长度的熊猫系列

问题描述

使用 pandas concat 函数可以创建如下系列:

In[230]pd.concat({'One':pd.Series(range(3)), 'Two':pd.Series(range(4))})
Out[230]: 
One  0    0
     1    1
     2    2
Two  0    0
     1    1
     2    2
     3    3
dtype: int64

不使用 concat 方法是否可以做同样的事情?我最好的方法是:

a = pd.Series(range(3),range(3))
b = pd.Series(range(4),range(4))
pd.Series([a,b],index=['One','Two'])

但它不一样,它输出:

One    0    0
       1    1
       2    2
dtype: int64

Two    0    0
       1    1
       2    2
       3    3
dtype: int64
dtype: object

标签: pythonpython-3.xpandas

解决方案


这应该让您了解它的用处concat

a.index = pd.MultiIndex.from_tuples([('One', v) for v in a.index])
b.index = pd.MultiIndex.from_tuples([('Two', v) for v in b.index])

a.append(b)

One  0    0
     1    1
     2    2
Two  0    0
     1    1
     2    2
     3    3
dtype: int64

同样的事情是通过pd.concat([a, b]).


推荐阅读