【问题标题】:pd DataFrame, need to add columns, parsing text string date_time into pandas year, dayOfWeek, etc in one passpd DataFrame,需要添加列,一次性将文本字符串date_time解析为pandas year、dayOfWeek等
【发布时间】:2021-05-18 11:24:15
【问题描述】:

需要说明:我从 SQLite 数据库执行了 cursor.fetchall 选择,返回 'id' 和 'date_time',后者是文本。我想使用 pd.to_date of year、dayOfWeek、dayOfYear、hourOfDay 创建其他列

问题:no-loop column add and population approach 为例,我尝试了多种调用组合,但均无效。

我首先测试了一系列调用,以确认我可以正确拆分测试日期;

sr = pd.Series(['2015-02-08 20:00:00']) 
sr = pd.to_datetime(sr) 

#Year: Series.dt.year The year of the datetime
#Day of week: Series.dt.dayofweek The day of the week with Monday=0, Sunday=6 
#Day of year: Series.dt.dayofyear The ordinal day of the year
#Hour: Series.dt.hour The hours of the datetime

print(sr)
print(sr.dt.year )
print(sr.dt.dayofweek )
print(sr.dt.dayofyear )
print(sr.dt.hour )

一切都按预期进行;

0 2015-02-08 20:00:00
数据类型:datetime64[ns]
0 2015 数据类型:int64
0 6
数据类型:int64
0 39
数据类型:int64
0 20
数据类型:int64

我尝试过的代码通过以下几行完美运行,返回 105,861 行 x 2 列;

def splitDateTime():
    try:
            sqliteConnection = sqlite3.connect('TestElecConsump.db')
            cursor = sqliteConnection.cursor()
            print("Connected to SQLite")
    
            sqlite_select_query = """SELECT id, date_time from WeatherRecord;"""
            cursor.execute(sqlite_select_query)
            records = cursor.fetchall()
            
            print("Total rows are:  ", len(records))
            print("Printing first row:", records[0])
            
            splitDatepd = pd.DataFrame(records, columns=['id','date_time']) 
            print("Dataframe shape:", splitDatepd.shape)
            print("Dataframe : " , splitDatepd, sep='\n')
        
            print ('records: ' + str(type(records)))
            print ('splitDatepd: ' + str(type(splitDatepd)))

但是,下一行执行时没有任何输出;

#Add new column of Pandas datetime year

splitDatepd["pd-datetime"] = splitDatepd.to-datetime["date_time"].dt.year

print("Dataframe shape:", splitDatepd.shape)
print("Dataframe : " , splitDatepd, sep='\n')

所以我决定通过省略 .year 解析来重复上述操作以简化问题;

splitDatepd["pd-datetime"] = splitDatepd.to-datetime["date_time"]

splitDatepd 仍然没有变化。

当 def 最终确定并返回数据帧时,它的打印输出看起来与 Select 语句中的原始数据帧完全相同。

我做错了什么?

【问题讨论】:

    标签: pandas dataframe sqlite datetime to-date


    【解决方案1】:

    您可以尝试在单个列中使用 pd.to_datetime 函数,例如:

    splitDatepd["pd_datetime"] = pd.to_datetime(splitDatepd["date_time"])

    PS:记住函数名使用下划线,我的意思是,它是pd.to_datetime 而不是pd.to-datetime

    【讨论】:

    • 这行得通,并允许我在返回年份的表达式末尾添加“.dt.year”,这样我就可以立即填充年份、星期几等。ty!
    猜你喜欢
    • 2020-06-05
    • 2020-11-19
    • 1970-01-01
    • 2022-01-23
    • 1970-01-01
    • 1970-01-01
    • 2019-09-29
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多