Skip to main content
 首页 » 编程设计

python之Pandas 将数据框转换为没有 None 的元组数组

2025年05月04日998°冷暖

我正在使用 Apriori 算法分析一些数据。这需要我将数据框转换为元组数组,每个元组对应于数据框的“行”。

In [1]: data 
Out[1]:  
     c1   c2   c3   c4   c5 
r1   a    b    c    d    None 
r2   a    b    c    None None 

我已经尝试了下面的代码,但其中仍然有一些“无”。我想删除它们。

In [2]: data = [tuple(x) for x in data.values] 
Out[2]:  
[('a','b','c','d',None),('a','b','c',None,None)] 

我希望这样的数据:

[('a','b','c','d'),('a','b','c')] 

请您参考如下方法:

使用带过滤的嵌套列表理解:

data = [tuple([y for y in x if y is not None]) for x in data.values] 
print (data) 
[('a', 'b', 'c', 'd'), ('a', 'b', 'c')] 

如果数据量大,则更慢的替代方案 - reshape 以删除 None 并按元组的第一级 MultiIndex 聚合:

data = data.stack().groupby(level=0).apply(tuple).tolist() 
print (data) 
[('a', 'b', 'c', 'd'), ('a', 'b', 'c')]