Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Subtract a column in pandas dataframe by its first value

I need to subtract all elements in one column of pandas dataframe by its first value.

In this code, pandas complains about self.inferred_type, which I guess is the circular referencing.

df.Time = df.Time - df.Time[0]

And in this code, pandas complains about setting value on copies.

df.Time = df.Time - df.iat[0,0]

What is the correct way to do this computation in Pandas?

like image 247
Dzung Nguyen Avatar asked Oct 27 '25 10:10

Dzung Nguyen


1 Answers

I think you can select first item in column Time by iloc:

df.Time = df.Time - df.Time.iloc[0]

Sample:

start = pd.to_datetime('2015-02-24 10:00')
rng = pd.date_range(start, periods=5)

df = pd.DataFrame({'Time': rng, 'a': range(5)})  
print (df)
                 Time  a
0 2015-02-24 10:00:00  0
1 2015-02-25 10:00:00  1
2 2015-02-26 10:00:00  2
3 2015-02-27 10:00:00  3
4 2015-02-28 10:00:00  4

df.Time = df.Time - df.Time.iloc[0]
print (df)
    Time  a
0 0 days  0
1 1 days  1
2 2 days  2
3 3 days  3
4 4 days  4

Notice:

For me works perfectly your 2 ways also.

like image 162
jezrael Avatar answered Oct 28 '25 23:10

jezrael