本文探讨如何在Python Pandas中,根据上一行值高效创建并累加新列。 问题并非简单地使用apply函数就能解决,需要结合Pandas特性巧妙实现。
假设数据包含三列(‘col1’, ‘col2’, ‘col3’),目标是根据’col1’创建’col4’列:’col1’值在(3, 5)之间则’col4’为1,否则为0;且’col4’中值为1的连续数值进行累加。
直接使用循环遍历方法虽然清晰,但效率低:
values = [[5.5, 2.5, 10.0], [2.0, 4.5, 1.0], [2.5, 5.2, 8.0], [4.5, 5.8, 4.8], [4.6, 6.3, 9.6], [4.1, 6.4, 9.0], [5.1, 2.3, 11.1], [4.8, 2.3, 4.8], [4.8, 2.3, 4.8]]df = pd.DataFrame(values, columns=['col1', 'col2', 'col3'], index=['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'y'])col4 = []index = 1for one in df['col1']: if 3 < one < 5: index += 1 col4.append(index) else: index = 0 col4.append(index)df['col4'] = col4
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。