Skip to main content
 首页 » 编程设计

嵌套在数据框中的列表上的 Python 绝对值

2025年05月04日18findumars

我有一个这样的数据框:

Current Dataframe: 
 
   ID       Price   Price_List 
0  Prodt1   1500    [-5.2, -4.6, -3.3, 0] 
1  Prodt2   17      [-9.2, -8.4, -2.1, 0] 

我想将绝对值应用于 Price_List 中的列表(零值除外),并将其添加回自身,然后对其进行排序。结果列如下所示:

Desired Dataframe: 
 
   ID       Price   Price_List               New_Col 
0  Prodt1   1500    [-5.2, -4.6, -3.3, 0]    [-5.2, -4.6, -3.3, 0, 3.3, 4.6, 5.2] 
1  Prodt2   17      [-9.2, -8.4, -2.1, 0]    [-9.2, -8.4, -2.1, 0, 2.1, 8.4, 9.2] 

非常感谢任何帮助!

请您参考如下方法:

您可以使用列表推导式遍历 Price_List 中的列表,并使用除 0 之外的所有元素的绝对值和条件表达式扩展每个列表(注意if j 就足够了,因为仅当 j 为 0 时,表达式的计算结果为 False:

df['New_Col'] = sorted(i + [abs(j) for j in i if j] for i in df.Price_List) 

print(df) 
 
     ID    Price         Price_List                    New_Col 
0  Prodt1   1500  [-5.2, -4.6, -3.3, 0]  [-5.2, -4.6, -3.3, 0, 3.3, 4.6, 5.2] 
1  Prodt2     17  [-9.2, -8.4, -2.1, 0]  [-9.2, -8.4, -2.1, 0, 2.1, 8.4, 9.2]