基于字符串拆分复制Pandas Dataframe行,无需迭代

时间:2017-08-30 16:07:35

标签: python python-3.x pandas

我有一个带有多索引的数据框,其中一列代表多个值,由" |"分隔,如下所示:

            value
left right 
x    a|b    2
y    b|c|d  -1

我想基于"右边"复制行。专栏,得到这样的东西:

           values
left right
x    a     2
x    b     2
y    b     -1
y    c     -1
y    d     -1

我对此的解决方案感觉不对而且运行缓慢,因为它基于迭代:

df2 = df.iloc[:0]
for index, row in df.iterrows():
    stgs = index[1].split("|")
    for s in stgs:
        row.name = (index[0], s)
        df2 = df2.append(row)

有没有更传时的方法来做到这一点?

1 个答案:

答案 0 :(得分:0)

Pandas系列有专门的方法split来执行此操作

split仅适用于Series,因此请隔离所需的列

SO = df['right']

现在同时执行3个步骤:spilt返回一系列数组。 apply(pd.Series, 1)在列中转换数组。 stack将您的列堆叠为一个唯一的列

S1 = SO.str.split(',').apply(pd.Series, 1).stack()

唯一的问题是你现在有一个多索引。所以只需降低你不需要的水平

S1.index.droplevel(-1)

完整示例

SO = pd.Series(data=["a,b", "b,c,d"])

S1 = SO.str.split(',').apply(pd.Series, 1).stack()
S1
Out[4]:
0  0    a
   1    b
1  0    b
   1    c
   2    d

S1.index = S1.index.droplevel(-1) 
S1 
Out[5]:
0    a
0    b
1    b
1    c
1    d