gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 08:25:05 25 4
gpt4 key购买 nike

我有一个这样的数据框:

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 就足够了,因为仅当 j0 时,表达式的计算结果为 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]

关于嵌套在数据框中的列表上的 Python 绝对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58058732/

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