Finger Bruno
Finger Bruno

Reputation: 39

how to append value in a dataframe column

I'm trying to se the evolution of my invetimens over the time and I'm stuck in a problem. When I try to loop the initial value x variation, I get a full NaN column

here's the code

value = 1000
total = []

for variation in df["Variation"]:
    value = value * variation
    total.append(value)

I've tryed the same algorithm and worked

list=[1,2,3,4,5]
a = 2
results = []

for x in list:
    a = a * x
    results.append(a)

where is the mistake?

Upvotes: 2

Views: 1865

Answers (2)

tdy
tdy

Reputation: 41487

Instead of looping, a more pandas-like approach would be cumprod():

df = pd.DataFrame({'Variation': [1, 2, 3, 4, 5]})

value = 2
total = df.Variation.cumprod() * value

# 0      2
# 1      4
# 2     12
# 3     48
# 4    240
# Name: Variation, dtype: int64

Per the nan comments, note that cumprod() would also handle nan seamlessly:

df = pd.DataFrame({'Variation': [np.nan, 2, 3, 4, 5]})

value = 2
total = df.Variation.cumprod() * value

# 0      NaN
# 1      4.0
# 2     12.0
# 3     48.0
# 4    240.0
# Name: Variation, dtype: float64

Upvotes: 2

unaied
unaied

Reputation: 307

This should do it

for variation in df["Variation"].tolist():
    value = value * variation
    total.append(value)

Upvotes: 1

Related Questions