1

I have list of tuples that looks like given below in a Pandas column.

0     [(1, 2)]
1          [(6, 1)]
2     [(8, 10), 4+]
3                []
4        [0.6, 1.5]
5                []
6              [2+]
7          [(0, 1)]
8                []
9                []
10        [0.7, 1+]
11               []
12         [(2, 3)]
13         [(1, 3)]
14               []
15               []
16               []
17             [2+]
18               []
19               []

I want to remove tuples and make a simple list of each row. I use the code

df['clean']=df['mix'].apply(lambda x: [ele for tup in x for ele in tup] )

the issue is that the float values are split and thats not desired. I dont understand what am I doing wrong.

0                 [1, 2]
1                 [6, 1]
2          [8, 10, 4, +]
3                     []
4     [0, ., 6, 1, ., 5]
5                     []
6                 [2, +]
7                 [0, 1]
8                     []
9                     []
10       [0, ., 7, 1, +]
11                    []
12                [2, 3]
13                [1, 3]
14                    []
15                    []
16                    []
17                [2, +]
18                    []
19                    []
Sid
  • 552
  • 6
  • 21

2 Answers2

0

Use custom function for flatten iterables like tuples, but not strings (because there are not floats, but string repr of floats):

#https://stackoverflow.com/a/2158532
def flatten(l):
    for el in l:
        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):
            yield from flatten(el)
        else:
            yield el

df['clean']=df['mix'].apply(lambda x: list(flatten(x)))
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • Thanks @jezrael, I figured out a way to fix while I was waiting for an answer. I have posted it below. – Sid Jun 05 '20 at 05:49
  • 1
    @Sid - Super, also is possible use `isinstance(li[i], tuple)` for test tuples – jezrael Jun 05 '20 at 05:50
0

The answer given by @jezrael works well, though I had solve the issue by the following method

def Tups2List(li):
clean_list=[]
"""check if the element in the list is a tuple, if yes, go into tuple 
and add add elements to the result list, else loop through the list 
and append the elements to the final list"""
for i in range(len(li)):
    if type(li[i])==tuple:
        for j in range(len(li[i])):
            clean_list.append(li[i][j])
    else:
        clean_list.append(li[i])
return clean_list
Sid
  • 552
  • 6
  • 21