[英]Need to convert entire column from string format to date format from a Dataframe
I am trying to convert an entire column from a Dataframe from a string to date format. 我正在尝试将数据框的整个列从字符串转换为日期格式。 Does anyone have any recommendations on how to do this?
是否有人对此有任何建议?
I've successfully been able to change one element of this using strptime, but not sure the best way to apply this to the entire column: 我已经能够使用strptime成功更改其中的一个元素,但是不确定将其应用于整个列的最佳方法:
Sample of the raw Data: 原始数据样本:
2016/06/28 02:13:51
In: 在:
Var1 = Dataframename['columnname'][0]
temp = datetime.datetime.strptime(Var1, '%Y/%m/%d %H:%M:%S')
temp
Out: 日期:
datetime.datetime(2016, 6, 28, 2, 13, 51)
I think you are looking for this 我想你在找这个
import datetime
data['colname']=data['colname'].apply(lambda x:datetime.datetime.strptime(x,"%Y-%m-%d %H:%M:%S"))
You can use to_datetime
: 您可以使用
to_datetime
:
df = pd.DataFrame({'b':['2016/06/28 02:13:51','2016/06/28 02:13:51','2016/06/28 02:13:51'],
'a':[4,5,6]})
print (df)
a b
0 4 2016/06/28 02:13:51
1 5 2016/06/28 02:13:51
2 6 2016/06/28 02:13:51
df['b'] = pd.to_datetime(df.b)
print (df)
a b
0 4 2016-06-28 02:13:51
1 5 2016-06-28 02:13:51
2 6 2016-06-28 02:13:51
print (df.dtypes)
a int64
b datetime64[ns]
dtype: object
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.