将数据帧转换为另一个数据帧,将复合字符串单元格拆分为单独的行 [英] Convert data frame to another data frame, split compound string cell into individual rows

查看:70
本文介绍了将数据帧转换为另一个数据帧,将复合字符串单元格拆分为单独的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在寻找使用Python将数据帧df1转换为df2的方法.我有一个使用循环的解决方案,但我想知道是否有更简单的方法来创建df2.

I am looking to convert data frame df1 to df2 using Python. I have a solution that uses loops but I am wondering if there is an easier way to create df2.

df1

   Test1   Test2   2014  2015  2016  Present
1     x        a     90    85    84        0
2     x      a:b     88    79    72        1
3     y    a:b:c     75    76    81        0
4     y        b     60    62    66        0
5     y        c     68    62    66        1

df2

   Test1  Test2   2014  2015  2016  Present
1     x       a     90    85    84        0
2     x       a     88    79    72        1
3     x       b     88    79    72        1
4     y       a     75    76    81        0
5     y       b     75    76    81        0
6     y       c     75    76    81        0
7     y       b     60    62    66        0
8     y       c     68    62    66        1

推荐答案

这是使用numpy.repeatitertools.chain的一种方法:

Here's one way using numpy.repeat and itertools.chain:

import numpy as np
from itertools import chain

# split by delimiter and calculate length for each row
split = df['Test2'].str.split(':')
lens = split.map(len)

# repeat non-split columns
cols = ('Test1', '2014', '2015', '2016', 'Present')
d1 = {col: np.repeat(df[col], lens) for col in cols}

# chain split columns
d2 = {'Test2': list(chain.from_iterable(split))}

# combine in a single dataframe
res = pd.DataFrame({**d1, **d2})

print(res)

   2014  2015  2016  Present Test1 Test2
1    90    85    84        0     x     a
2    88    79    72        1     x     a
2    88    79    72        1     x     b
3    75    76    81        0     y     a
3    75    76    81        0     y     b
3    75    76    81        0     y     c
4    60    62    66        0     y     b
5    68    62    66        1     y     c

这篇关于将数据帧转换为另一个数据帧,将复合字符串单元格拆分为单独的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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