vahid vhr
vahid vhr

Reputation: 5

.iloc and for loop in pandas to add new column

there is a dataframe like:

import pandas as pd
df = pd.DataFrame([[11, 21], [24, 15], [17, 48], [28, 31], [22, 14]],columns=['A', 'B'])

enter image description here

so I want to add new column in name "C". but I want "C" calculate

base on "A" as "C"[i]="A"[i]-"A"[i-1] formula.

I wrote two kinds method but they did not work.

first method):

for i in (0,5)
    df['c'].iloc[i]=df['A'].iloc[i]- df['A'].iloc[i-1]
print(df)

second):

for i in (0,5)
    df.iloc['c',i]=df.iloc['A',i]- df.iloc['A',i-1]
print(df)

could someone guide?

Upvotes: 1

Views: 744

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195438

You can use .shift():

df["C"] = df.A - df.A.shift(1)
print(df)

Prints:

    A   B     C
0  11  21   NaN
1  24  15  13.0
2  17  48  -7.0
3  28  31  11.0
4  22  14  -6.0

Upvotes: 1

Related Questions