2017-03-03 59 views
-3

我在csv文件中有一些數據,它有一些MM/DD/YYYY格式的條目和一些DD-MM-YYYY格式的條目。我想閱讀這一列的條目,並將其作爲熊貓數據框中的新列進行存儲?我會怎麼做呢?將MM/DD/YYYY轉換爲DD-MM-YYY

例子:

Entry  Sampling Date 
    1   01-10-2004 
    2   01-13-2004 
    3   16/1/2004 

我想前兩行的日期格式轉換爲第三排。

+0

'.replace( 「/」, 「 - 」)'? – WhatsThePoint

+1

@WhatsThePoint:交換月份和日期.. –

+0

@MartijnPieters是的,我錯過了 – WhatsThePoint

回答

1

使用datetime模塊,定義一個函數,然後將它應用到你的列

import datetime.datetime 

def read_date(string): 
    if '/' in entry: 
     date = datetime.datetime.strptime(string,'%m/%d/%Y') 
    elif '-' in entry: 
     date = datetime.datetime.strptime(string, '%d-%m-%Y') 
    return date 

# If df is your dataframe 
df['newdate'] = df['Sampling Date'].apply(read_date) 
+0

我認爲這會起作用。但是,正如我在上面的評論中提到的那樣,這一年沒有全部提及,2004年1月3日寫爲03-01-04。這給我錯誤。 – Raghuram

+0

這不是你在你的例子中顯示的內容...然後只需用%y替換%Y,那樣做就可以了。很明顯,如果你有一些截斷年份和其他年份的完整行,你將不得不做一個if子句來選擇解析方法 – LoicM

+0

是的,我意識到這不是我在示例中展示的。我的錯。感謝你的回答。它現在有效 – Raghuram