2015-05-04 92 views
0

我有一個數據框,看起來像這樣。熊貓數據框應用功能

df.head() 
    Ship Date Cost Amount 
0 2010-08-01 4257.23300 
1 2010-08-01 9846.94540 
2 2010-08-01 35.77764 
3 2010-08-01 420.82920 
4 2010-08-01 129.49638 

我不得不俱樂部數據一週明智的,我做到了:

df['week_num'] = pd.DatetimeIndex(df['Ship Date']).week 
x = df.groupby('week_num').sum() 

它產生一個數據幀,看起來像這樣:

  Cost Amount 
week_num  
30  3.273473e+06 
31  9.715421e+07 
32  9.914568e+07 
33  9.843721e+07 
34  1.065546e+08 
35  1.087598e+08 
36  8.050456e+07 

現在我想增加一列與周和年的信息做我做的:

def my_conc(row): 
    return str(row['week_num'])+str('2011') 

x['year_week'] = x.apply(my_conc,axis= 1) 

這給了我一個錯誤信息:

KeyError: ('week_num', u'occurred at index 30') 

現在我的問題是 1)爲什麼GROUPBY函數生成的數據幀,看起來有點古怪,因爲它不具備WEEK_NUM作爲列名稱 ? 2)是否有更好的方法來生成分組數據的數據框? 3)如何在上面的數據框中使用apply函數temp

+0

你怎麼會'df.groupby( 'WEEK_NUM')。SUM()'?當'df'沒有'week_num'列的時候。 – Zero

+0

@JohnGalt,對不起,我錯過了一箇中間步驟。我現在添加了它。 –

回答

1

這裏有一種方法去做吧。

使用as_index=Falsegroupby不創建索引。

In [50]: df_grp = df.groupby('week_num', as_index=False).sum() 

然後apply lambda函數。

In [51]: df_grp['year_week'] = df_grp.apply(lambda x: str(x['week_num']) + '2011', 
              axis=1) 

In [52]: df_grp 
Out[52]: 
    week_num  Cost year_week 
0  30 3273473 302011 
1  31 97154210 312011 
2  32 99145680 322011 
3  33 98437210 332011 
4  34 106554600 342011 
5  35 108759800 352011 
6  36 80504560 362011 

或者使用df_grp.apply(lambda x: '%d2011' % x['week_num'], axis=1)

+0

它工作正常!只是另一個問題,大熊貓是否認可週日組合作爲日期類型呢? –

0

關於你的第一個問題,我不知道。當我嘗試複製它時,我只是得到一個錯誤。

在其他問題,請使用GROUPBY的.DT訪問()函數...

# get your data into a DataFrame 
data = """Ship Date Cost Amount 
0 2010-08-01 4257.23300 
1 2010-08-01 9846.94540 
2 2010-08-01 35.77764 
3 2010-08-01 420.82920 
4 2010-08-01 129.49638 
""" 
from StringIO import StringIO # import from io for Python 3 
df = pd.read_csv(StringIO(data), header=0, index_col=0, sep=' ', skipinitialspace=True) 

# make the dtype for the column datetime64[ns] 
df['Ship Date'] = pd.to_datetime(df['Ship Date']) 

# then you can use the .dt accessor to group on 
x = df.groupby(df['Ship Date'].dt.dayofyear).sum() 
y = df.groupby(df['Ship Date'].dt.weekofyear).sum() 

還有更多的這些.DT訪問器的主機... link

+0

它似乎沒有工作。它會拋出一個錯誤''Series'對象沒有屬性'dt'' –

+0

您需要更改數據類型:pd.to_datetime(df ['Ship Date']) –

+0

我已經完成了該操作。 'df ['發貨日期']'是dt屬性不存在的系列。 –