2017-03-01 33 views
2

我在我的數據框中有一些列,我只想保留日期部分並刪除時間部分。我列出了這些列:將地圖()用於熊貓數據框中的列

list_of_cols_to_change = ['col1','col2','col3','col4'] 

我已經寫了一個這樣做的函數。它獲取列的列表並將dt.date應用於列表中的每個列。

def datefunc(x): 
    for column in x: 
     df[column] = df[column].dt.date 

我再調用這個函數傳遞列表作爲參數:

datefunc(list_of_cols_to_change) 

我要做到這一點使用類似的地圖()。基本上使用一個函數,它將一列作爲參數並對其進行更改。然後我想使用map()將這個函數應用到我擁有的列的列表中。類似這樣的:

def datefunc_new(column): 
    df[column] = df[column].dt.date 

map(datefunc_new,list_of_cols_to_change) 

但是這不起作用。我該如何做這項工作?

回答

2

最簡單的是使用lambda功能apply

df = pd.DataFrame({'col1':pd.date_range('2015-01-02 15:00:07', periods=3), 
        'col2':pd.date_range('2015-05-02 15:00:07', periods=3), 
        'col3':pd.date_range('2015-04-02 15:00:07', periods=3), 
        'col4':pd.date_range('2015-09-02 15:00:07', periods=3), 
        'col5':[5,3,6], 
        'col6':[7,4,3]}) 

print (df) 
       col1    col2    col3 \ 
0 2015-01-02 15:00:07 2015-05-02 15:00:07 2015-04-02 15:00:07 
1 2015-01-03 15:00:07 2015-05-03 15:00:07 2015-04-03 15:00:07 
2 2015-01-04 15:00:07 2015-05-04 15:00:07 2015-04-04 15:00:07 

       col4 col5 col6 
0 2015-09-02 15:00:07  5  7 
1 2015-09-03 15:00:07  3  4 
2 2015-09-04 15:00:07  6  3 

list_of_cols_to_change = ['col1','col2','col3','col4'] 
df[list_of_cols_to_change] = df[list_of_cols_to_change].apply(lambda x: x.dt.date) 
print (df) 
     col1  col2  col3  col4 col5 col6 
0 2015-01-02 2015-05-02 2015-04-02 2015-09-02  5  7 
1 2015-01-03 2015-05-03 2015-04-03 2015-09-03  3  4 
2 2015-01-04 2015-05-04 2015-04-04 2015-09-04  6  3 
2

我想你已經有解決方案,只需添加column作爲參數傳遞給你的datefunc_new功能:

def datefunc_new(column): 
    df[column] = df[column].dt.date 

map(datefunc_new, list_of_cols_to_change) 

你也可以使用一個更大熊貓喜歡代碼爲您具體的例子:

def to_date(series): 
    return series.dt.date 

df[list_of_cols_to_change] = df[list_of_cols_to_change].apply(to_date)