我的数据框中有一些列,我只想保留日期部分并删除时间部分。我列出了这些列:
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()之类的方法来完成此任务。基本上使用将列作为参数并对其进行更改的函数。然后,我想使用map()将此功能应用于我拥有的列的列表。像这样:
def datefunc_new(column):
df[column] = df[column].dt.date
map(datefunc_new,list_of_cols_to_change)
但是,这不起作用。我该如何工作?
最简单的是使用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
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句