Pandas Get First Element of Each Tuple in Cell
Asked Answered
B

3

5

Given the following data frame:

import pandas as pd
df=pd.DataFrame({'A':['a','b','c'],
                 'B':[[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]],[[1,2],[3,4],[5,6]]]})
df

    A               B
0   a   [[1, 2], [3, 4], [5, 6]]
1   b   [[1, 2], [3, 4], [5, 6]]
2   c   [[1, 2], [3, 4], [5, 6]]

I'd like to create a new column ('C') containing the first value in each element of the tuple of column B like this:

    A               B                 C
0   a   [[1, 2], [3, 4], [5, 6]]   [1,3,5]
1   b   [[1, 2], [3, 4], [5, 6]]   [1,3,5]
2   c   [[1, 2], [3, 4], [5, 6]]   [1,3,5]

So far, I've tried:

df['C']=df['B'][0]

...but that only returns the first tuple ([1, 2]).

Thanks in advance!

Beau answered 12/7, 2016 at 16:30 Comment(3)
won't df['B'].apply(lambda x: [e[0] for e in x]) work? OK just re-read it, see updated commentEliason
Yes, indeed. Are you going to post as an answer?Beau
No need Alberto's answer is what I would've postedEliason
A
8
df['C'] = df['B'].apply(lambda x: [y[0] for y in x])
Arms answered 12/7, 2016 at 16:37 Comment(0)
E
11

This works for me -

df['C'] = df['B'].str[0]
Eveleen answered 29/3, 2021 at 19:24 Comment(1)
This worked for me as well, getting a int value out of a tuple[int,int,int]Nerve
A
8
df['C'] = df['B'].apply(lambda x: [y[0] for y in x])
Arms answered 12/7, 2016 at 16:37 Comment(0)
L
2

try this:

df['C'] =   df["B"].apply(lambda x : [y[0] for y in list(x)])
Libel answered 12/7, 2016 at 16:36 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.