Skip to content Skip to sidebar Skip to footer

Python: Applying A Function To Dataframe Taking Input From The New Calculated Column

Im facing a problem with applying a function to a DataFrame (to model a solar collector based on annual hourly weather data) Suppose I have the following (simplified) DataFrame: df

Solution 1:

It sounds like you are calculating a cumulative sum. In that case, use cumsum:

In [45]: df['D'] = (df['A']+df['B']+df['C']).cumsum()

In [46]: df
Out[46]: 
    A   B  C   D
0  11  13  5  29
1   6   7  4  46
2   8   3  6  63
3   4   8  7  82
4   0   1  7  90

[5 rows x 4 columns]

Solution 2:

Are you looking for this? You can use shift to align the previous row with current row and then you can do your operation.

In [7]: df
Out[7]:
   a  b
1  1  1
2  2  2
3  3  3
4  4  4

[4 rows x 2 columns]

In [8]: df['c'] = df['b'].shift(1) #First row will be Nan

In [9]: df
Out[9]:
   a  b   c
1  1  1 NaN
2  2  2   1
3  3  3   2
4  4  4   3

[4 rows x 3 columns]

Post a Comment for "Python: Applying A Function To Dataframe Taking Input From The New Calculated Column"