Search code examples
pandasoverwritecombinelatest

Combine a part of values


I have a Dataframe like this:

In: 
daten["Gas"].head(5)

Out: 
2016-12-09 10:22:00       2.1
2016-12-09 10:22:15       5.1
2016-12-09 10:22:30       3.2
2016-12-09 10:22:45       2.0
2016-12-09 10:23:00       1.1

And i will do a calculation with a Part of these Values and put them back into the column.

von = pd.to_datetime("12.09.16 10:22:15",infer_datetime_format=True)
bis = pd.to_datetime("12.09.16 10:22:45",infer_datetime_format=True)
auswahl = daten.loc[von:bis]
auswahl["Gas_neu"] = auswahl["Gas"] - 2 // just an example

new Out:
2016-12-09 10:22:00 2.1
2016-12-09 10:22:15 3.1
2016-12-09 10:22:30 1.2
2016-12-09 10:22:45 0.0
2016-12-09 10:23:00 1.1

sadly .combine dont work in this case, is there another way?

this is the calculation

auswahl["Gas_1"] = auswahl["Gas"]

auswahl["Gas_1"] = (auswahl["Gas_1"] - auswahl["Gas_1"].shift()).fillna(0)

auswahl["Gas_1"] = auswahl["Gas_1"] * 2400


Solution

  • You can use:

    daten.loc[von:bis, 'Gas'] -=  2
    print (daten)
                         Gas
    2016-12-09 10:22:00  2.1
    2016-12-09 10:22:15  3.1
    2016-12-09 10:22:30  1.2
    2016-12-09 10:22:45  0.0
    2016-12-09 10:23:00  1.1
    

    What is same as:

    daten.loc[von:bis, 'Gas'] =  daten.loc[von:bis, 'Gas'] - 2
    print (daten)
                         Gas
    2016-12-09 10:22:00  2.1
    2016-12-09 10:22:15  3.1
    2016-12-09 10:22:30  1.2
    2016-12-09 10:22:45  0.0
    2016-12-09 10:23:00  1.1
    

    And for new column:

    daten.loc[von:bis, 'Gas_neu'] =  (daten.loc[von:bis, 'Gas'] - 2)
    daten['Gas_neu'] = daten['Gas_neu'].fillna(daten['Gas'])
    print (daten)
                         Gas  Gas_neu
    2016-12-09 10:22:00  2.1      2.1
    2016-12-09 10:22:15  5.1      3.1
    2016-12-09 10:22:30  3.2      1.2
    2016-12-09 10:22:45  2.0      0.0
    2016-12-09 10:23:00  1.1      1.1
    

    Solution without filtering:

    daten['Gas_1'] = (daten["Gas"] - daten["Gas"].shift()).fillna(0).mul(2400)
    daten['Gas_2'] = daten["Gas"].diff().fillna(0).mul(2400)
    print (daten)
                         Gas   Gas_1   Gas_2
    2016-12-09 10:22:00  2.1     0.0     0.0
    2016-12-09 10:22:15  5.1  7200.0  7200.0
    2016-12-09 10:22:30  3.2 -4560.0 -4560.0
    2016-12-09 10:22:45  2.0 -2880.0 -2880.0
    2016-12-09 10:23:00  1.1 -2160.0 -2160.0
    

    And with filtering:

    von = pd.to_datetime("12.09.16 10:22:15",infer_datetime_format=True)
    bis = pd.to_datetime("12.09.16 10:22:45",infer_datetime_format=True)
    daten.loc[von:bis, 'Gas_neu'] =  daten.loc[von:bis, 'Gas'].diff().fillna(0).mul(2400)
    daten['Gas_neu'] = daten['Gas_neu'].fillna(daten['Gas'])
    print (daten)
                         Gas  Gas_neu
    2016-12-09 10:22:00  2.1      2.1
    2016-12-09 10:22:15  5.1      0.0
    2016-12-09 10:22:30  3.2  -4560.0
    2016-12-09 10:22:45  2.0  -2880.0
    2016-12-09 10:23:00  1.1      1.1