python - 熊猫爆炸并删除多列的重复项
问题描述
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
解决方案
我有另一种使用stack
, then的方法explode()
,我认为您可以尝试一下。cumcount
unstack
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
推荐阅读
- r - 当函数使用 enquo 列时,如何将多个函数传递给 purr::map(exec 或 invoke_map)?
- android - 在 Android 应用上仅显示部分 webview
- html - 图像上的css过滤器亮度而不是文本覆盖
- ios - Xcode 11.1 - 找不到身份命令 PhaseScriptExecution 失败,退出代码为非零
- c# - UWP UserControl 大小正确但未呈现
- c++ - Libtins TCP流丢失数据包?
- r - 拆分具有不同行数的列,包括标题
- sql - 从 AWS S3 Parquet 文件复制数据 - 仅限于几行
- google-cloud-platform - Terraform:Cloud Run 服务上的 Cloud Endpoints?
- spring-batch - 带有 Rest API 的 Spring Batch 启动/停止