首页 > 解决方案 > 熊猫爆炸并删除多列的重复项

问题描述

explode尝试在多 (4) 列上执行时遇到一些问题。第一个问题是,MemoryError如果我尝试一次炸开所有列,我会遇到这种情况。单独爆炸每一列后有许多重复项,因此我可以使用drop_duplicates(),但是由于lists列中存在它引发的TypeError: unhashable type: 'list'。如果我将列转换为字符串,astype(str)则这些列不能与.explode(). pd.eval()因此,如果我在执行第二个之前尝试到该列,.explode()我会得到UndefinedVariableError: name 'nan' is not defined. 这是示例数据集:

    id     col_1      col_2   col_3   col_4 
0    1 ['a','b']        nan   ['c']     nan   
1    2       nan  ['d','e']     nan     nan
2    3     ['f']        nan     nan     nan
3    4       nan      ['g']     nan     nan 
4    5       nan        nan   ['h']     nan
5    6       nan        nan   ['i']   ['j'] 

这是当前代码:

for i in new_table:
    new_table = new_table.explode(i)
    new_table = new_table.astype(str)
    new_table = new_table.drop_duplicates()
    new_table['col_1'] = pd.eval(new_table['col_1'])
    new_table['col_2'] = pd.eval(new_table['col_2'])
    new_table['col_3'] = pd.eval(new_table['col_3'])
    new_table['col_4'] = pd.eval(new_table['col_4'])

pd.eval()加注UndefiniedVariableError: name 'nan' is not defined。_ 如果我删除最后 4 行,那么这些列将被解释为字符串,并且在第二个循环中,explode()由于输入是字符串,而不是列表,所以不会做任何事情。但是我必须(?)将列转换为字符串以执行drop_duplicates().

用于重新创建示例数据集的代码:

new_table = pd.DataFrame({'id':[1,2,3,4,5,6],
                          'col_1':[['a','b'],np.nan,['f'],np.nan,np.nan,np.nan],
                          'col_2':[np.nan,['d','e'],np.nan,['g'],np.nan,np.nan],
                          'col_3':[['c'],np.nan,np.nan,np.nan,['h'],['i']],
                          'col_4':[np.nan,np.nan,np.nan,np.nan,np.nan,['j']]})

预期输出:

id     col_1      col_2   col_3   col_4 
1          a        nan       c     nan
1          b        nan       c     nan
2        nan          d     nan     nan
2        nan          e     nan     nan
3          f        nan     nan     nan
4        nan          g     nan     nan
5        nan        nan       h     nan
6        nan        nan       i       j

标签: pythonpandas

解决方案


我有另一种使用stack, then的方法explode(),我认为您可以尝试一下。cumcountunstack

s= new_table.set_index('id').stack(dropna=True).explode().to_frame('s')
final = (s.set_index(s.groupby(s.index.get_level_values(-1))
                              .cumcount(),append=True)['s'].unstack(1))
final = final.groupby(level=0).apply(lambda x: 
                      x.ffill().bfill()).drop_duplicates().droplevel(1)

print(final)

    col_1 col_2 col_3 col_4
id                        
1      a   NaN     c   NaN
1      b   NaN     c   NaN
2    NaN     d   NaN   NaN
2    NaN     e   NaN   NaN
3      f   NaN   NaN   NaN
4    NaN     g   NaN   NaN
5    NaN   NaN     h   NaN
6    NaN   NaN     i     j

推荐阅读