高手帮我解释下我写的代码逻辑错误在哪里

pandas题目:根据以下数据,需要增加一列 c,c 列的计算逻辑是:
第一行的值为所在行的 a + b,第二行及以后的值为 上一行的 c + a
我理解写的代码如下:
df = pd.DataFrame({‘a’: [5, 6, 7], ‘b’: [3, 5, 8]})
print(df)
def func(i):
if len(i)==1:
return i.a+i.b
else:
return i.a.sum()+i.b[0]
print(df.expanding().apply(func))

出错提示:AttributeError: ‘Series’ object has no attribute ‘a’
可能对函数生成的数据类型理解不深,高手帮我解释下

讨论数量: 2
import pandas as pd

df = pd.DataFrame({'a': [5, 6, 7], 'b': [3, 5, 8]})

def func(i):
    if i == 0:
        return df.iloc[i].a + df.iloc[i].b
    else:
        return df.at[i-1, 'c'] + df.iloc[i].a

df['c'] = df.index.map(func)

print(df)
1年前 评论
# !/usr/bin/python3

import pandas as pd

df = pd.DataFrame({'a': [5, 6, 7], 'b': [3, 5, 8]})

c = []


def func(i):
    if i == 0:
        number = df.iloc[i].a + df.iloc[i].b
    else:
        number = c[i - 1] + df.iloc[i].a
    c.append(number)
    return number


df['c'] = df.index.map(func)
1年前 评论

讨论应以学习和精进为目的。请勿发布不友善或者负能量的内容,与人为善,比聪明更重要!