将按日期索引的数据框拆分为带有包含相关事件值的每月列的数据框

时间:2018-09-12 15:44:43

标签: python pandas dataframe

我有一个数据框,其中包含按日期索引的每月降雨量值。这是一个简短的代码段:

Name

我需要产生一个新的数据框,其中每个月的列都包含在闷热期(20年)中每个相关月的值。

例如...

      date  ppt
      ...
2016-11-30  253.379993
2016-12-31  52.709998
2017-01-31  9.030000
2017-02-28  10.050000
2017-03-31  16.560000
2017-04-30  45.509998
2017-05-31  103.829997
      ...

有人可以帮忙吗?

谢谢!

编辑:

到目前为止,我已经尝试过:

    Jan   Feb    Mar   Apr   May  ...  
0   
1
2
3
4
5
...

但是,尽管我将索引明确设置为datetime,但是它返回了此错误...

df.pivot_table(index=df.date.dt.year, columns=df.date.dt.month, values='ppt')

3 个答案:

答案 0 :(得分:3)

为月份和年份分配一列,并使用pivot

df.assign(month=df.date.dt.month,year=df.date.dt.year).pivot('year','month','ppt')

在您的情况下,它给出:

month    1      2      3          4           5           11         12
year                                                                   
2016    NaN    NaN    NaN        NaN         NaN  253.379993  52.709998
2017   9.03  10.05  16.56  45.509998  103.829997         NaN        NaN

答案 1 :(得分:3)

使用pivot_table

df.pivot_table(index=df.date.dt.year, columns=df.date.dt.month, values='ppt')

date    1      2      3          4           5           11         12
date
2016   NaN    NaN    NaN        NaN         NaN  253.379993  52.709998
2017  9.03  10.05  16.56  45.509998  103.829997         NaN        NaN

答案 2 :(得分:0)

无法执行上述建议后,我设法找到了解决方法。虽然涉及更多步骤,但无法找出错误所在的挫败感远远超过了额外的代码行的工作量。

#pragma section(".code", execute, read)
#pragma section(".codedata", read, write)
#pragma comment(linker,"/SECTION:.code,ERW")
#pragma comment(linker,"/SECTION:.codedata,ERW")
#pragma comment(linker, "/MERGE:.codedata=.code")

//All the following will go in code
#pragma code_seg(".code")
#pragma data_seg(".codedata")
#pragma const_seg(".codedata")

//CODE TO DECRYPT

// .stub SECTION
#pragma section(".stub", execute, read)
#pragma section(".stubdata", read, write)
#pragma comment(linker,"/SECTION:.stub,ERW")
#pragma comment(linker,"/SECTION:.stubdata,ERW")
#pragma comment(linker, "/MERGE:.stubdata=.stub")

//All the following will go in .stub segment
#pragma code_seg(".stub")
#pragma data_seg(".stubdata")
#pragma const_seg(".stubdata")

/*This function needs to be changed to whatever correspond to the decryption function of the encryotion function used by the encryptor*/
void decryptCodeSection(){

     //Retrieve virtual address of the pointer to the .code section
     //Retrieve the virtual size of the pointer to the .code section
     for(int i = 0; i<size; i++){
          //HERE THE PROGRAM STOPS
          ptrCode[0] = //Reverse function of the encryptor
      }

void main(int argc, char* argv[]){
    decryptor();
    mainFunctionDecrypted();
}

尽管如此,还是谢谢大家的建议:)