[英]Pandas: sum values two columns consisting of lists
我有一个像这样的Pandas数据框。
id discount current_price
01188 [0, 0, 0, 78] [0, 294, 294, 294, 294, 294, 294, 294, 294, 294]
列discount
和price
均由整数列表组成。 我想创建一个名为old_price
的新列,其中包含discount
和price
元素之和。
因此,新列将具有: [0, 294, 294, 372, 294, 294, 294, 294, 294, 294]
我会在这里使用带有itertools.zip_longest
旧列表列表。 如果您设置使用DataFrame中的列表,这可能是最快的。
from itertools import zip_longest
df.assign(old_price=[
[x + y for x, y in zip_longest(d, c, fillvalue=0)]
for d, c in zip(df.discount, df.current_price)
])
id discount current_price old_price
0 1188 [0, 0, 0, 78] [0, 294, 294, 294, 294, 294, 294, 294, 294, 294] [0, 294, 294, 372, 294, 294, 294, 294, 294, 294]
如果所有行的长度都相同,则可以优化数据的存储方式,但这又取决于数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.