Ganesh Shinde
Ganesh Shinde

Reputation: 49

How to get the previous value of the same row (previous column) from the pandas dataframe?

I want to fetch the value from the previous column but the same row and I need to multiply that value with 5 and write it to the current place.

I have tried shift method of pandas but it's not working. after that, I have written the separate function to get the previous column name..but I think that's not the good approach.

'''
def get_previous_column_name(wkName):
        v = int(wkName.strip('W'))
        newv = str(v - 1)
        if len(newv) == 1:
            newv = '0' + newv
        return 'W' + newv
'''

dataframe: 

W01,W02,W03,W04,W05
7, 8
10,20
20, 40

expected result: 

W01,W02,W03,W04,W05
7, 8, 40, 200, 1000
10, 20, 100, 500, 2500
20, 40, 200, 1000, 5000

Upvotes: 1

Views: 148

Answers (3)

DYZ
DYZ

Reputation: 57033

If you indeed have only three columns to fill, just do the multiplication:

df['W03'] = df['W02'] * 5
df['W04'] = df['W03'] * 5
df['W05'] = df['W04'] * 5
df
#   W01  W02  W03   W04   W05
#0    7    8   40   200  1000
#1   10   20  100   500  2500
#2   20   40  200  1000  5000

Upvotes: 0

Rebin
Rebin

Reputation: 526

import pandas as pd
data = pd.read_csv('C:/d1', sep=',', header=None,names=['W1','W2'])
df=pd.DataFrame(data)
dfNew=pd.DataFrame(columns=['W1','W2','W3','W4','W5'])
(rows,columns)=df.shape

for index in range(rows):
    tempRow=[df.iat[index,0],df.iat[index,1],df.iat[index,1]*5,df.iat[index,1]*25,df.iat[index,1]*125]
    dfNew.loc[len(dfNew)]=tempRow

print()
print(dfNew)

Upvotes: 0

BENY
BENY

Reputation: 323286

Here is one way ffill +cumsum

df=df.ffill(1)*(5)**df.isnull().cumsum(1)
df
Out[230]: 
    W01   W02    W03     W04     W05
0   7.0   8.0   40.0   200.0  1000.0
1  10.0  20.0  100.0   500.0  2500.0
2  20.0  40.0  200.0  1000.0  5000.0

Upvotes: 2

Related Questions