将元组转换为 Pandas 中的列表时,浮动元素被错误拆分

Float element are wrongly split when converting tuples to list in Pandas

我有元组列表,如下面的 Pandas 列所示。

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               []

我想删除元组并为每一行制作一个简单列表。我使用代码

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

问题是浮点值被拆分了,这不是我们想要的。我不明白我做错了什么。

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                    []

使用自定义函数来展平元组之类的可迭代对象,而不是字符串(因为没有浮点数,但是浮点数的字符串 repr):

#
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 给出的答案很好,虽然我已经通过以下方法解决了问题

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