Subtract a column in pandas dataframe by its first value

╄→гoц情女王★ 提交于 2020-01-04 17:30:46

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39991471/subtract-a-column-in-pandas-dataframe-by-its-first-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!