Skip to main content
 首页 » 编程设计

python之如何更改 Pandas 数据框中的日期

2024年10月17日9tuyile006

我有如下数据框

     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 

但是效果不是很好 我该如何转型?

请您参考如下方法:

可以使用numpy,先通过values转成numpy数组然后通过 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 

另一个较慢的解决方案:

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