gpt4 book ai didi

python - Pandas 爆炸并删除多列的重复项

转载 作者:行者123 更新时间:2023-12-05 02:56:47 25 4
gpt4 key购买 nike

我在尝试对多 (4) 列执行 explode 时遇到一些问题。第一个问题是,如果我尝试一次展开所有列,我会遇到 MemoryError。分别分解每一列后有很多重复项,因此我可以使用 drop_duplicates(),但是由于列中有 lists,它引发了 TypeError: unhashable type: '列表'。如果我使用 astype(str) 将列转换为字符串,则这些列不能与 .explode() 一起使用。因此,如果我在执行第二个 .explode() 之前尝试 pd.eval() 列,我会得到 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() 引发了 UndefinedVariableError: 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

最佳答案

你能不能像这样:

df[['id']].join((df[i].explode() for i in df.iloc[:,1:]))

输出:

|    |   id | col_1   | col_2   | col_3   | col_4   |
|---:|-----:|:--------|:--------|:--------|:--------|
| 0 | 1 | a | nan | c | nan |
| 0 | 1 | b | nan | c | nan |
| 1 | 2 | nan | d | nan | nan |
| 1 | 2 | nan | 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 |

注意,我认为你在做什么和我在做什么的主要区别在于你在数据框上使用 explode,因此你的数据框对于你调用的每一列都是重复的.然后,您只选择“分解的”columna 并加入新的数据框。

我正在做的是分解每一列 (pd.Series) 并将每个“分解”系列的结果连接到索引上。我不会创建一堆额外的列,这些列是在数据框上使用 explode 时创建的。

关于python - Pandas 爆炸并删除多列的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60152241/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com