Home > Net >  Divide list or dataframe after certain value
Divide list or dataframe after certain value

Time:09-30

I have a list that looks like this:

list = ['A', '0', '1', '2', 'B', '3', '5', '6']

I would like to create either DataFrames or lists that go such as:

A = ['0, 1 ,2']
    
B = ['3', '5', '6']

Basically assigning the values between letter and letter to a separate list.

I have tried several methods but can't seem to make it work.

CodePudding user response:

You can do

df = pd.DataFrame({'col1' : l})
df['col2'] = df.col1.where(df.col1.str.isalpha()).ffill()
df = df.query('col1!=col2')
df
  col1 col2
1    0    A
2    1    A
3    2    A
5    3    B
6    5    B
7    6    B

CodePudding user response:

you can try as following :

code

import re     
list_ = ['A', '0', '1', '2', 'B', '3', '5', '6','C','7','8','9']
new_li = re.split('[A-Z]', ''.join(list_))

dict_ = {}
for i, y in enumerate(new_li):
    lists_ = [char for char in y]
    dict_['li'   str(i)] = lists_
dicts_ = dict([(k,v) for k,v in dict_.items() if len(v)>0])

Output

dicts_
Out[1]: {'li1': ['0', '1', '2'], 'li2': ['3', '5', '6'], 'li3': ['7', '8', '9']}

You can translate dictionary to list or pandas dataframe depends on your needs.

  • Related