2016-10-14 63 views
1

我有數據幀像下面如何更改日期在大熊貓數據幀

 day 
0 2016-07-12 
1 2016-08-13 
2 2016-09-14 
3 2016-10-15 
4 2016-11-01 

dtype:datetime64 

我想改變這一天像下面

 day 
0 2016-07-01 
1 2016-08-01 
2 2016-09-01 
3 2016-10-01 
4 2016-11-01 

我試圖

df.day.dt.day=1 

但它沒有工作得很好 我該如何轉換?

回答

2

您可以使用numpy,首先轉換爲numpy arrayvalues,然後通過astype轉換爲datetime64[M],什麼是最快的解決方案:

df['day'] = df['day'].values.astype('datetime64[M]') 
print (df) 
     day 
0 2016-07-01 
1 2016-08-01 
2 2016-09-01 
3 2016-10-01 
4 2016-11-01 

另一個slowier解決方案:

df['day'] = df['day'].map(lambda x: pd.datetime(x.year, x.month, 1)) 
print (df) 
     day 
0 2016-07-01 
1 2016-08-01 
2 2016-09-01 
3 2016-10-01 
4 2016-11-01 

計時

#[50000 rows x 1 columns] 
df = pd.concat([df]*10000).reset_index(drop=True) 

def f(df): 
    df['day'] = df['day'].values.astype('datetime64[M]') 
    return df 

print (f(df))  

In [281]: %timeit (df['day'].map(lambda x: pd.datetime(x.year, x.month, 1))) 
10 loops, best of 3: 160 ms per loop 

In [282]: %timeit (f(df)) 
100 loops, best of 3: 4.38 ms per loop