'For a dataframe, convert all list in a column to int values

My current daraframe is:

id   name    class
1     A      [1, 1, 1]
2     B      [2, 2]
3     C      [3]
4     D      [6,6]

all elements in any list will be the same so instead of exploding, we can join only the first element.

All I want my dataframe to look something like this:

id   name    class
1     A        1
2     B        2
3     C        3
4     D        6

Please help me how can I code this. Thanks.



Solution 1:[1]

Asuming there is atleast 1 element in the list you can apply a lambda function to the class column and set it to the 0th index.

Code

df = pd.DataFrame({ 
    'name': ['A', 'B', 'C', 'D'], 
    'class': [ [1,1,1], [2,2], [3], [6, 6]]
})

df['class'] = df['class'].apply(lambda x: x[0])   # Add this to your code

Output

enter image description here

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1