2017-08-07 26 views
3

我應該怎麼做,如果我只是想在timestamp列顯示2016-06-29擁有並刪除不需要的部分像15:46:43.895000在大熊貓刪除列不需要的內容(而不是整個列)

enter image description here

+0

能告訴你,你已經試過的任何代碼? –

+0

如果我的(或其他)答案有幫助,請不要忘記[接受](http://meta.stackexchange.com/a/5235/295067) - 點擊答案旁邊的複選標記('✓')將其從灰色切換到填充。謝謝。 – jezrael

回答

1

如果時間戳:

df['timestamp'] = df['timestamp'].dt.floor('d') 

如果字符串:

df['timestamp'] = df['timestamp'].str.split().str[0] 

樣品:

df = pd.DataFrame({'timestamp':pd.date_range('2016-06-29 15:46:43.895000', 
           periods=3, 
           freq='2000T')}) 
print (df) 
       timestamp 
0 2016-06-29 15:46:43.895 
1 2016-07-01 01:06:43.895 
2 2016-07-02 10:26:43.895 

print (type(df.loc[0, 'timestamp'])) 
<class 'pandas._libs.tslib.Timestamp'> 

df['timestamp'] = df['timestamp'].dt.floor('d') 
print (df) 
    timestamp 
0 2016-06-29 
1 2016-07-01 
2 2016-07-02 

df = pd.DataFrame({'timestamp':['2016-06-20 15:46:43.895000', 
           '2016-06-22 15:46:43.895000', 
           '2016-06-29 15:46:43.895000']}) 
print (df) 
        timestamp 
0 2016-06-20 15:46:43.895000 
1 2016-06-22 15:46:43.895000 
2 2016-06-29 15:46:43.895000 

print (type(df.loc[0, 'timestamp'])) 
<class 'str'> 

df['timestamp'] = df['timestamp'].str.split().str[0] 
print (df) 
    timestamp 
0 2016-06-20 
1 2016-06-22 
2 2016-06-29 
1

我們可以使用.dt.normalize()方法:

df['timestamp'] = df['timestamp'].dt.normalize() 
0
df['timestamp']=pd.to_datetime(df['timestamp']).dt.strftime('%Y-%m-%d')