Search code examples
pythonpandasjupyteranalytics

How can I add the value of an observation in a column with an observation from another column


Hey guys so I have this issue Who can help me with code or an algorithm that will take fd.loc[0, ‘value 4’] and add it to fd.loc[1, ‘value 2] to give the output of fd.loc[1, ‘value 4’] basically i want every observation in value 4 to be the sum of its previous observation and the corresponding observation in value 2 (i hope explain my problem properly)

dict = {
'value 1' : [1,2,3],
'value 2' : [4,5,6]
}

fd = pd.DataFrame(dict)
fd['value 4'] = 10 + fd['value 2']
fd

Solution

  • If the 'value 4'-column already exists and you want to transform those values as you describe, you can do it like this:

    fd['value 4'] = fd['value 2'] + fd['value 4'].shift()
    

    Then you will just have to reassign fd.loc[0, ‘value 4’], which is now NaN, and maybe recast the whole column to integer, as it has been converted to float because of the missing value.