pandas:如何将一列中的文本拆分为多行? [英] pandas: How do I split text in a column into multiple rows?
问题描述
我正在处理一个大型 csv 文件,最后一列的下一列有一个我想用特定分隔符拆分的文本字符串.我想知道是否有一种简单的方法可以使用 Pandas 或 Python 来做到这一点?
I'm working with a large csv file and the next to last column has a string of text that I want to split by a specific delimiter. I was wondering if there is a simple way to do this using pandas or python?
CustNum CustomerName ItemQty Item Seatblocks ItemExt
32363 McCartney, Paul 3 F04 2:218:10:4,6 60
31316 Lennon, John 25 F01 1:13:36:1,12 1:13:37:1,13 300
我想在 Seatblocks
列中用空格(' ')
和冒号(':')
分开,但是每个单元格将导致不同数量的列.我有一个重新排列列的功能,因此 Seatblocks
列位于工作表的末尾,但我不确定从那里开始做什么.我可以使用内置的 text-to-columns
函数和一个快速宏在 excel 中完成,但我的数据集有太多记录,excel 无法处理.
I want to split by the space(' ')
and then the colon(':')
in the Seatblocks
column, but each cell would result in a different number of columns. I have a function to rearrange the columns so the Seatblocks
column is at the end of the sheet, but I'm not sure what to do from there. I can do it in excel with the built in text-to-columns
function and a quick macro, but my dataset has too many records for excel to handle.
最终,我想记录 John Lennon 的记录并创建多行,将每组座位的信息放在单独的行上.
Ultimately, I want to take records such John Lennon's and create multiple lines, with the info from each set of seats on a separate line.
推荐答案
这将按空间拆分座垫,并为每个座垫分配自己的行.
This splits the Seatblocks by space and gives each its own row.
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
或者,在其自己的列中给出每个以冒号分隔的字符串:
Or, to give each colon-separated string in its own column:
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
这有点难看,但也许有人会提出更漂亮的解决方案.
This is a little ugly, but maybe someone will chime in with a prettier solution.
这篇关于pandas:如何将一列中的文本拆分为多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!