Posting minimal reproducible example
I have a dataframe say
JavaScript
x
6
1
df
2
combined
3
0 [0, 0, 1, 0, 0, 1, 0, 1]
4
1 [1, 0, 0, 0, 0, 1, 1, 0]
5
2 [1, 0, 0, 0, 1]
6
I need to create a new column where values will be only from the alternate index.
JavaScript
1
5
1
new_column
2
0 [0, 1, 0, 0]
3
1 [1, 0, 0, 1]
4
2 [1, 0, 1]
5
This is what I tried, but this does not work
JavaScript
1
2
1
df['combined'].str[::2]
2
P.S : There are numerous ways in which this can be achieved I am looking for a more pandaic
approach
Advertisement
Answer
You may need to check your cell type is list if not do ast
JavaScript
1
4
1
import ast
2
df['combined'] = df['combined'].apply(ast.literal_eval)
3
df['combined'].str[::2]
4