Home > Back-end >  Join into one list in Python
Join into one list in Python

Time:07-09

I had a DataFrame which I processed like so:

df = my_table[0]

df_position = df['Position'].replace({'-':','}, regex=True)

That gave me a result like this:

0  1,2,3,4
1  4,5,6,7
2  7,8,9,10
3  10,11,12,13

How can I put the data in a single list, like this?

[1,2,3,4,4,5,6,7,7,8,9,10,10,11,12,13]

CodePudding user response:

IIUC, you can join the values together with , then split the whole thing on , and convert the values to int:

[int(v) for v in ','.join(df_position).split(',')]

Output:

[1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13]

If you want to operate directly on the dataframe, you could use this instead (joining and splitting on -):

[int(v) for v in '-'.join(df['Position']).split('-')]

Output:

[1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13]

CodePudding user response:

Use Series.str.split(',') to split the values on comma, then call explode to make it vertically long, then call to_list to get list out of it. Using df.iloc[:,0] assuming that you are interested in first column's values.

>>> df_position.iloc[:,0].str.split(',').explode().astype('int').to_list()

[1, 2, 3, 4, 4, 5, 6, 7, 7, 8, 9, 10, 10, 11, 12, 13]
  • Related