如何在Pandas数据帧中将对象转换为日期时间?

时间:2014-02-25 19:32:59

标签: python pandas

我有以下代码从CSV文件导入

    data = pd.read_csv(("dados_meteo.csv"),\
               names=['POM','DTM','RNF','WET','HMD','TMP','DEW','INF'],\
               parse_dates = ['DTM'])

然后

 data.dtypes

返回

POM     object
DTM     object
RNF    float64
WET    float64
HMD    float64
TMP    float64
DEW    float64
INF      int64
dtype: object

使用后

data['DTM'] = data['DTM'].astype('datetime64[ns]')

DTM保持相同的类型。你能帮帮我吗?

谢谢

2 个答案:

答案 0 :(得分:1)

检查您的CSV文件日期列,并确保将其设置为日期类型(或者选择列=&gt;右键单击=&gt;格式化单元格=&gt;在类别下选择日期=&gt;并选择日期格式)< / p>

然后

data =pd.read_csv("dados_meteo.csv",parse_dates=['date-coumn-name-here'])

答案 1 :(得分:0)

创建数据框后,您可以将对象转换为日期时间类型。  这是我做的方式

# -*- coding: utf-8 -*-
from pynput import keyboard

def on_press(key):
    try:
        moje = format(key.char)
    except AttributeError:
        print('special key {0} pressed'.format(key))

def on_release(key):
    #print('{0} released'.format(key).encode('utf-8'))
    #print('{0} released'.format(key).encode('cp437'))
    a = format(key)
    a = a.encode('cp437')
    print a #<-- here are "bad" chars produced / especially decoding issues / it shows unicode string but I am not able to show it properly, or save it to file, it shows/saves u'\u010d' instead of č
#     import codecs
#     f = codecs.open("test", "w", "utf-8-sig")
#     #f = open('test', 'w')
#     f.write(a) #<-- here are "bad" chars produced / especially decoding issues / it shows unicode string but I am not able to show it properly, or save it to file, it shows/saves u'\u010d' instead of č
#     f.close()
#     f = file('test', 'r')
#     print f.read().decode('cp437')
#     print u'\u0420\u043e\u0441\u0441\u0438\u044f'
    #print  u'não vou esqueçer mais de usar o u no começo' 
    if key == keyboard.Key.esc:
        # Stop listener
        return False

# Collect events until they are released
with keyboard.Listener(
        on_press=on_press,
        on_release=on_release) as listener:
    listener.join()

如果原始数据中没有缺失值,则可能不需要使用errors ='ignore'

希望有所帮助!