将元组转换为熊猫中的列表时,浮动元素被错误地分割

问题描述 投票:0回答:2

我在下面的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                    []
python python-3.x pandas tuples nested-lists
2个回答
0
投票
将自定义函数用于像元组这样的扁平可迭代对象,而不是字符串(因为没有浮点数,而是浮点数的字符串代表):

#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)))


0
投票
@ 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

© www.soinside.com 2019 - 2024. All rights reserved.