如何根据日期创建单独的跟踪列? [英] How to create a separate tracking column based on dates?
本文介绍了如何根据日期创建单独的跟踪列?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据框,df:
I have a dataframe, df:
df:
val
date
2012-01-01 4.2
2012-01-02 3.7
2012-01-03 6.2
2012-01-04 1.2
2012-01-05 2.4
2012-01-06 2.3
我要创建的列是从 0 开始指定日期并相应地填充该列(假设本例中的日期为 2012-01-04):
What I want to create is a column that starts at 0 for a specified date and fills in the column accordingly (assume the date in this case is 2012-01-04):
df2:
val tracking
date
2012-01-01 4.2 -3
2012-01-02 3.7 -2
2012-01-03 6.2 -1
2012-01-04 1.2 0
2012-01-05 2.4 1
2012-01-06 2.3 2
我尝试使用 np.arange(),但无法以我需要的行为中心.日期列设置为索引(pandas df).
I tried using np.arange() but was having trouble centering on the row I needed. The date column is set up as an index (pandas df).
谢谢.
推荐答案
我认为最简单的方法是分两部分进行:
I think the easiest way to do this is to do it in two parts:
df['tracking'] = pd.np.arange(len(df))
In [12]: df
Out[12]:
val tracking
date
2012-01-01 4.2 0
2012-01-02 3.7 1
2012-01-03 6.2 2
2012-01-04 1.2 3
2012-01-05 2.4 4
2012-01-06 2.3 5
df['tracking'] -= df.ix['2012-01-04']['tracking']
In [14]: df
Out[14]:
val tracking
date
2012-01-01 4.2 -3
2012-01-02 3.7 -2
2012-01-03 6.2 -1
2012-01-04 1.2 0
2012-01-05 2.4 1
2012-01-06 2.3 2
这篇关于如何根据日期创建单独的跟踪列?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文