I would like to split each row into new columns based on several indices:
6ABCDE0218594STRING
to
6 ABCDE 021 8594 STRING
This seems like it'd have been asked at least once before, but I keep finding only variations on the question (separating by a delimiter as in pandas: How do I split text in a column into multiple rows? , separating into new rows using rather than new columns, again with a delimiter: Split pandas dataframe string entry to separate rows ).
I apologize in advance if this is a duplicate!
One way is to use a regex and str.extract to pull out the columns:
In [11]: df = pd.DataFrame([['6ABCDE0218594STRING']])
You could just do it with index, so something like this:
In [12]: df[0].str.extract('(.)(.{5})(.{3})(.{4})(.*)')
Out[12]:
0 1 2 3 4
0 6 ABCDE 021 8594 STRING
Or you could be a bit more cautious and ensure each column is the correct form:
In [13]: df[0].str.extract('(\d)(.{5})(\d{3})(\d{4})(.*)')
Out[13]:
0 1 2 3 4
0 6 ABCDE 021 8594 STRING
Note: You can also use named groups (see the docs ).
Try this:
string = '6ABCDE0218594STRING'
indices = [1,5,3,4]
myList = []
for index in indices:
token, string = string[:index],string[index:]
myList.append(token)
myList.append(string)
>>> Output: ['6', 'ABCDE', '021', '8594', 'STRING']
Or in case you don't know the number of digits, letters etc.:
import re
m = re.match('(\d*)([A-Z]*)(\d*)([A-Z]*)', '6ABCDE0218594STRING').groups()
print m[0], m[1], m[2], m[3]
Output:
6 ABCDE 0218594 STRING
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.