我有一个表(数据框)需要清理,每一行看起来像这样:
我想将其分成如下表。
所以想法是B列中的内容应该被分割并转换为多行,分隔符是一大块随机数(代码)。
我对 Python 很陌生,但自己也不太了解。我怎样才能做到这一点?谢谢!
最佳答案
使用 Series.str.findall
+ df.explode
组合:
df['Column B'] = df['Column B'].str.findall(r'(\d+[\s\D]+)')
df = df.explode('Column B')
Column A Column B
0 Cell 1 1234 abcd
0 Cell 1 667 randomthings
1 Cell 3 4455 abcd abc
1 Cell 3 847 other randomthings
1 Cell 3 1 endings
如果删除尾随空格很重要,请将正则表达式模式更改为 r'(\d+[\s\D]+[^\d\s])'
在findall
匹配。或申请df['Column B'] = df['Column B'].str.strip()
在第一次初始接近结束时。
关于Python如何在字符串中每次有一大块数字时分割列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75699249/