2017-02-02 4 views
3

Ich habe einen Datenrahmen mit 2 Spalten. col1 ist date und col2 ist bigint. Es gibt Dummy-Wert 1970-01-01 00:00:00 und 19700101000000Text in datetime Spalte zusammenführen

col1    col2 
2012-01-12 18:09:42 19700101000000 
1970-01-01 00:00:00 20140701000001 

ich nach einem Weg suchen, diese zwei Spalten in eine einzige Datetime-Spalte so zu verschmelzen ...

col3 
2012-01-12 18:09:42 
2014-07-01 00:00:01 

Oder ist es eine Möglichkeit, zu fusionieren Text von Spalte col2 in col1.

Antwort

1

Sie müssen zuerst to_datetime und dann to_timedelta, zuletzt col1 hinzufügen:

print (pd.to_datetime(df.col2, format='%Y%m%d%H%M%S')) 
0 1970-01-01 00:00:00 
1 2014-07-01 00:00:01 
Name: col2, dtype: datetime64[ns] 

print (pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S'))) 
0  0 days 00:00:00 
1 16252 days 00:00:01 
Name: col2, dtype: timedelta64[ns] 

df.col1 = pd.to_datetime(df.col1) 
df['col3'] = pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S')) + df.col1 
print (df) 
       col1   col2    col3 
0 2012-01-12 18:09:42 19700101000000 2012-01-12 18:09:42 
1 1970-01-01 00:00:00 20140701000001 2014-07-01 00:00:01 

Parameter unit kann auch verwendet werden:

df['col3'] = pd.to_timedelta(pd.to_datetime(df.col2, format='%Y%m%d%H%M%S'), unit='ns') + 
      df.col1 
print (df) 
       col1   col2    col3 
0 2012-01-12 18:09:42 19700101000000 2012-01-12 18:09:42 
1 1970-01-01 00:00:00 20140701000001 2014-07-01 00:00:01 
Verwandte Themen