2017-10-20 72 views
0

從列(Python Pandas)獲取最早的日期我從多列CSV文件加載一些數據。在我的csv.reader中我有一個IF函數。我正在嘗試從特定列(開始日期)獲取最早的日期。csv.reader

我首先加載數據:當我打印柱(的startDate)

for row in csv.reader(open('myFile.csv')): 
    if row[4] == '56886': 
    key = row[4] #key = (row[4], row[33][:4], row[4]) 
    startDate = row[19] 

我正在此:使用下述

enter image description here

01)我想:

content = min(content) 
print(content) 

我在終端上得到了這個:

enter image description here

02)然後我試圖改變我的代碼:

for row in csv.reader(open('myFile.csv', 
     parse_dates=['Start Date'], 
     usecols=['Start Date'])) 
    if row[4] == '56886': 
    key = row[4] #key = (row[4], row[33][:4], row[4]) 
    startDate = row[19] 

,我得到了一個無效的語法錯誤

03)我試圖改變行:

pandas.read_csv('myFile.csv', parse_dates=['Start Date'], usecols=['Start Date']) 

,我得到了同樣的錯誤。

什麼是最好的解決方法?到目前爲止我還沒有找到解決方案。

+0

使用熊貓,你可以使用'pd.to_datetime(df [「Start Date」])來轉換一個完整的柱子' – Sosel

回答

1

我認爲你需要boolean indexing過濾:

#dont filter all columns by usecols  
df = pd.read_csv('file', parse_dates=['Start Date', 'End Date']) #columns to datetimes 

#filter output first by column ID and then get min and max 
a = df.loc[ df['ID'] == 56886, 'Start Date'].min() 


b = df.loc[ df['ID'] == 56886, 'End Date'].max() 
0

使用大熊貓給一個單一的項目轉換的一個例子:

pd.to_datetime("08/27/2017") 

用熊貓來轉換字符串的一個列表中的一個例子:

times = [] 
for i in range(30): 
    times.append(str(i+1)+"/01/2016") 
datetimes = pd.to_datetime(times) 
min(datetimes)