繁体   English   中英

熊猫:求和两列包含列表的值

[英]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]

discountprice均由整数列表组成。 我想创建一个名为old_price的新列,其中包含discountprice元素之和。

因此,新列将具有: [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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM