Skip to content
Advertisement

How to split AFTER underscore in Python

I’ve seen a lot of threads that say how to split based on an underscore, but how can we split a string where the split is done after the underscore.

So let’s say I have a pandas dataframe with one column:

 item
100_5151
101_1205
102_8153
...

how can I achieve the following output?

  item      id    group
100_5151   100_   5151 
101_1205   101_   1205 
102_8153   102_   8153
...

Thanks in advance.

Advertisement

Answer

You can split with the _ as a separator and then add again the _ to the id string:

id, group =item.split("_")
id=id+"_"
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement