2013-10-25 96 views
1

我报下一个数据帧了2006 colunms在大熊猫拆分列

data=read_csv('enero.csv') 
data 

      Fecha   DirViento MagViento 
0 2011/07/01 00:00  318  6.6  
1 2011/07/01 00:15  342  5.5   
2 2011/07/01 00:30  329  6.6   
3 2011/07/01 00:45  279  7.5   
4 2011/07/01 01:00  318  6.0   
5 2011/07/01 01:15  329  7.1   
6 2011/07/01 01:30  300  4.7   
7 2011/07/01 01:45  291  3.1   

如何在两列列出生日期拆分,例如,得到一个数据帧如下:

 Fecha  Hora  DirViento MagViento 
0 2011/07/01 00:00  318  6.6  
1 2011/07/01 00:15  342  5.5   
2 2011/07/01 00:30  329  6.6   
3 2011/07/01 00:45  279  7.5   
4 2011/07/01 01:00  318  6.0   
5 2011/07/01 01:15  329  7.1   
6 2011/07/01 01:30  300  4.7   
7 2011/07/01 01:45  291  3.1 

我正在使用熊猫来读取数据

我尝试从每月数据库计算每日平均值,每15分钟记录一次每日数据。要做到这一点,利用熊猫和分组的列:日期和时间为得到一个数据帧如下:

Fecha Hora 
2011/07/01 00:00 -4.4 
      00:15 -1.7 
      00:30 -3.4 
2011/07/02 00:00 -4.5 
      00:15 -4.2 
      00:30 -7.6 
2011/07/03 00:00 -6.3 
      00:15 -13.7 
      00:30 -0.3 

这一下,我得到以下

grouped.mean()                   

Fecha  DirRes 
2011/07/01 -3 
2011/07/02 -5 
2011/07/03 -6 
+0

这没有回答我的问题。 – aIKid

+1

将Fecha作为实际的日期时间对象是不是更好?将parse_dates = ['Fecha']传递给read_csv。 –

+0

我同意@AndyHayden,你可以传递给'read_csv'一个'parse_dates'参数,这将读取字符串并尝试解析它为一个日期时间,就像这样:'data = read_csv('enero.csv',parse_dates = ['日期星'])' – EdChum

回答

4

这里是一个link到相当以前已经回答过的类似问题,希望对您有所帮助。在你的情况下,你可以通过空格分割Fecha中的内容并构建字符串第二部分的列表。然后将内容添加到插入的新列

import pandas as p 
t = p.read_csv('test2.csv') 

#store into a data frame 
df = p.DataFrame(t) 


#update the fecha col value and create new col hora 
lista = [item.split(' ')[2] for item in df['Fecha']] 
listb = p.Series([item.split(' ')[0] for item in df['Fecha']]) 
df['Fecha'].update(listb) 
df['Hora'] = lista 

#change Hora position 
#I am not sure whether this is efficient or not 
#as I am also quite new to Pandas 
col = df.columns.tolist() 
col = col[-1:]+col[:-1] 
col[0], col[1] = col[1], col[0] 

df = df[col] 

print df 

希望这可以解决您的问题,这里是输出。

 Fecha Hora DirViento MagViento 
0 2011/07/01 00:00  318  6.6 
1 2011/07/01 00:15  342  5.5 
2 2011/07/01 00:30  329  6.6 
3 2011/07/01 00:45  279  7.5 
4 2011/07/01 01:00  318  6.0 
5 2011/07/01 01:15  329  7.1 
6 2011/07/01 01:30  300  4.7 
7 2011/07/01 01:45  291  3.1