BigSecrect BigSecrect - 7 months ago 5
Python Question

join corresponding column to dataframe pandas

I have an example dataframe looks like below. I want to make a calculation then append the result as a new column to current dataframe.

A, B # this is my df, a csv file
1, 2
3, 3
7, 6
13, 14


Below is some code I have tried.

for i in range(0,len(df.index)+1,1):
if len(df.index)-1 == i:
df['C'] = str(df.iloc[i]['A'] / df.iloc[i]['B'])
else:
df['C'] = str((df.iloc[i+1]['A'] - df.iloc[i]['A']) / (df.iloc[i+1]['B'] - df.iloc[i]['B'])) # I need string as dtype

df.to_csv(Out, index = False)


This only gives me the result of final loop, not corresponding result depending on each calculation.

A B C
1 2 2
3 3 1.33
7 6 0.75
13 14 0.93 # It is the result I'd like to see.


Does anyone know how to revise it? Thanks in advance!

Answer

UPDATE: - much more elegant solution (one-liner) from @root:

In [131]: df['C'] = (df.A.shift(-1).sub(df.A, fill_value=0) / df.B.shift(-1).sub(df.B, fill_value=0)).round(2).astype(str)

In [132]: df
Out[132]:
    A   B     C
0   1   2   2.0
1   3   3  1.33
2   7   6  0.75
3  13  14  0.93

In [133]: df.dtypes
Out[133]:
A     int64
B     int64
C    object
dtype: object

you can do it this way:

df['C'] = (df.A.shift(-1) - df.A) / (df.B.shift(-1) - df.B)
df.loc[df.index.max(), 'C'] = df.loc[df.index.max(), 'A'] / df.loc[df.index.max(), 'B']
df.round(2)

yields:

In [118]: df.round(2)
Out[118]:
    A   B     C
0   1   2  2.00
1   3   3  1.33
2   7   6  0.75
3  13  14  0.93