我在pandas df
中有一个表格 product_id_x product_id_y count
0 2727846 7872456 1
1 29234 2932348 2
2 29346 9137500 1
3 29453 91365738 1
4 2933666 91323494 1
我想添加我在str。
中定义的新列"日期"dateSelect = "'2016-11-06'"
所以我添加了一个新的常数列
df['dates'] = dateSelect
但我得到的结果为
product_id_x product_id_y count dates
0 2727846 7872456 1 '2016-11-06'
1 29234 2932348 2 '2016-11-06'
2 29346 9137500 1 '2016-11-06'
3 29453 91365738 1 '2016-11-06'
4 2933666 91323494 1 '2016-11-06'
日期中的值以引号为单位。和
type(df['dates']) = str
,但我希望以日期格式,因为我将进一步将此表存储在我的MySQL数据库中。我希望类型是日期。
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqldb://name:pwd@xxx.xx.xx.x/dbname', echo=False)
df.to_sql(name='tablename', con=engine, if_exists = 'append', index=False)
最直接路由
df['dates'] = pd.Timestamp('2016-11-06')
df
product_id_x product_id_y count dates
0 2727846 7872456 1 2016-11-06
1 29234 2932348 2 2016-11-06
2 29346 9137500 1 2016-11-06
3 29453 91365738 1 2016-11-06
4 2933666 91323494 1 2016-11-06
我认为您可以在空空间中使用第一个replace
'
,然后to_datetime
:
dateSelect = pd.to_datetime("'2016-11-06'".replace("'",""))
print (dateSelect)
2016-11-06 00:00:00
print (type(dateSelect))
<class 'pandas.tslib.Timestamp'>
df['dates'] = pd.to_datetime("'2016-11-06'".replace("'",""))
print (df)
product_id_x product_id_y count dates
0 2727846 7872456 1 2016-11-06
1 29234 2932348 2 2016-11-06
2 29346 9137500 1 2016-11-06
3 29453 91365738 1 2016-11-06
4 2933666 91323494 1 2016-11-06
print (df.dtypes)
product_id_x int64
product_id_y int64
count int64
dates datetime64[ns]
dtype: object
啊!@Jezrael首先到达那里...
print timeit.timeit("""
import pandas as pd
import datetime as dt
import timeit
df = pd.read_csv('date_time_pandas.csv')
dateSelect_str = "2016-11-06"
# using standard datetime
dateSelect = dt.datetime.strptime(dateSelect_str,"%Y-%m-%d")
df['dates'] = dateSelect
#print(df['dates'])
""",number=100)
# Alternate method using pandas datetime
print timeit.timeit("""
import pandas as pd
import datetime as dt
import timeit
df = pd.read_csv('date_time_pandas.csv')
dateSelect_str = "2016-11-06"
dateSelect = pd.to_datetime(dateSelect_str, format='%Y-%m-%d', errors='ignore')
df['dates'] = dateSelect
#print df['dates']
""",number=100)
给出输出 -
0.228258825751
0.167258402887
平均。
结论在这种情况下,使用pd_datetime更有效
在其中不要避免将其定义为字符串。
dateSelect = '2016-11-06'
df['dates'] = dateSelect
为日期范围pd.date_range函数是最好的。
dataFrame["Date Column"] = pd.date_range("1/08/2020", periods=len(dataFrame))
最好!