Home > database >  extracting a list within a list in a tuple which happens to be in a pd.series
extracting a list within a list in a tuple which happens to be in a pd.series

Time:02-07

x =[[(a,[b]), (c,[d]), (e,[f]).........]]

type(x)

pandas.core.series.Series

I want to create a series that only contains the values of the list within the tuple such as those[b] or [d] or [f].

How can I extract? Thank you.

CodePudding user response:

This Should Work:

old = [[('a', ['b']), ('c', ['d']), ('e', ['f'])]]


def main():
    for item in old:
        for sub_item in item:
            yield sub_item[1]


for x in main():
    print(x)

CodePudding user response:

Use:

x =[('a',['b']), ('c',['d']),('e',['f'])]
x1 = pd.Series(x)
x1.apply(lambda y: y[1])

The result:

enter image description here

Based on your comment:

temp = pd.Series(["[[('aaaa', ['bbbb']), ('cccc', ['ddddd'])]]", "[[('a',['b']), ('c',['d']), ('e',['f'])]]"])
temp.apply(lambda x: [x[1] for x in eval(x)[0]])

And, the result:

enter image description here

CodePudding user response:

Given Series s,

x = [[('a',['b']), ('c',['d']), ('e',['f'])]]
s = pd.Series(x)

we can explode it and use the str accessor to get the second elements in each tuple:

s= s.explode().str[1].reset_index(drop=True)

Output:

0    [b]
1    [d]
2    [f]

Then if we want to create a Series from the elements in the lists, we can explode yet again:

s = s.explode()

Output:

0    b
1    d
2    f

CodePudding user response:

Use Series.str:

In [969]: x =[('a',['b']), ('c',['d']),('e',['f'])]
     ...: s = pd.Series(x)

In [971]: s.str[1]
Out[971]: 
0    [b]
1    [d]
2    [f]
dtype: object
  •  Tags:  
  • Related