Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Pandas get elements from a column containing list of values using index slicing

Posting minimal reproducible example

I have a dataframe say

df  
           combined
0    [0, 0, 1, 0, 0, 1, 0, 1]
1    [1, 0, 0, 0, 0, 1, 1, 0]
2             [1, 0, 0, 0, 1]

I need to create a new column where values will be only from the alternate index.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

       new_column
0    [0, 1, 0, 0]
1    [1, 0, 0, 1]
2    [1, 0, 1]

This is what I tried, but this does not work

df['combined'].str[::2]

P.S : There are numerous ways in which this can be achieved I am looking for a more pandaic approach

>Solution :

You may need to check your cell type is list if not do ast

import ast
df['combined'] = df['combined'].apply(ast.literal_eval)
df['combined'].str[::2]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading