python按行拆分表格_python – pandas:如何将一列中的文本拆分为多行?

这会将Seatblocks按空格分隔,并给出每个自己的行。

In [43]: df

Out[43]:

CustNum CustomerName ItemQty Item Seatblocks ItemExt

0 32363 McCartney, Paul 3 F04 2:218:10:4,6 60

1 31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300

In [44]: s = df['Seatblocks'].str.split(' ').apply(Series, 1).stack()

In [45]: s.index = s.index.droplevel(-1) # to line up with df's index

In [46]: s.name = 'Seatblocks' # needs a name to join

In [47]: s

Out[47]:

0 2:218:10:4,6

1 1:13:36:1,12

1 1:13:37:1,13

Name: Seatblocks, dtype: object

In [48]: del df['Seatblocks']

In [49]: df.join(s)

Out[49]:

CustNum CustomerName ItemQty Item ItemExt Seatblocks

0 32363 McCartney, Paul 3 F04 60 2:218:10:4,6

1 31316 Lennon, John 25 F01 300 1:13:36:1,12

1 31316 Lennon, John 25 F01 300 1:13:37:1,13

或者,在每个冒号分隔的字符串在自己的列中:

In [50]: df.join(s.apply(lambda x: Series(x.split(':'))))

Out[50]:

CustNum CustomerName ItemQty Item ItemExt 0 1 2 3

0 32363 McCartney, Paul 3 F04 60 2 218 10 4,6

1 31316 Lennon, John 25 F01 300 1 13 36 1,12

1 31316 Lennon, John 25 F01 300 1 13 37 1,13

这是一个有点丑陋,但也许有人会在一个漂亮的解决方案。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值