Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/347.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何将数据框中的DateTimeIndex更改为所有同一年?_Python_Pandas - Fatal编程技术网

Python 如何将数据框中的DateTimeIndex更改为所有同一年?

Python 如何将数据框中的DateTimeIndex更改为所有同一年?,python,pandas,Python,Pandas,我有这样的数据: Charge 1 Charge 2 observation_date 1970-01-31 35.535318 0.073390 1970-02-28 27.685739 0.050302 ... 2013-01-31 27.671290 0.296882 2013-02-28 26.647262 0.225714

我有这样的数据:

                   Charge 1     Charge 2
observation_date                      
1970-01-31        35.535318   0.073390
1970-02-28        27.685739   0.050302

...

2013-01-31        27.671290   0.296882
2013-02-28        26.647262   0.225714
2013-03-31        21.495699   0.362151
我如何重新索引数据(观察日期),以便所有年份都成为2013年

因此,1970-01-31变为2013-01-31,等等。我知道指数会多次相同

import pandas as pd
df = pd.read_table('data', sep='\s{2,}').set_index('observation_date')
df.index = pd.DatetimeIndex(df.index)
df.index = df.index + pd.DateOffset(year=2013)
print(df)
屈服

             Charge 1  Charge 2
2013-01-31  35.535318  0.073390
2013-02-28  27.685739  0.050302
2013-01-31  27.671290  0.296882
2013-02-28  26.647262  0.225714
2013-03-31  21.495699  0.362151

我将编写一个函数来更新年份。 我将在这里简要介绍一个示例

import pandas as pd
df = pd.DataFrame({'observation_date':["1970-01-31","1970-02-31","1970-04-31"]})
l= df.observation_date

def updateYear(x):
  n= x.split("-")
  n[0]="2013" #We replace the year data, which is the first value by 2013
  return "-".join(n)
print updateYear("1970-01-31")


df['b']= df["observation_date"].apply(lambda x:updateYear(str(x)))
print df
输出::

  observation_date           b
0       1970-01-31  2013-01-31
1       1970-02-31  2013-02-31
2       1970-04-31  2013-04-31
就你而言:

df= pd.read_csv(name)
df.index = df.index.apply(lambda x:updateYear(str(x)))

不确定我是否理解你的问题,但你可以搜索1970年开始的年份,替换为2013年

例如

新建日期=重新划分(“1970年”、“2013年”、“观察日期”)


这正是我想要的。谢谢。@user3914487在这种情况下,您应该接受答案作为有效答案。