我正在处理一个大的 csv 文件,倒数第二列有一个我想用特定分隔符分割的文本字符串。我想知道是否有使用 pandas 或 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 处理。
最终,我想记录约翰列侬的记录并创建多条线路,每组座位的信息放在单独的线路上。
最佳答案
这会按空间分割座位区,并为每个座位区分配自己的行。
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
这有点难看,但也许有人会提出更漂亮的解决方案。
https://stackoverflow.com/questions/17116814/