【问题标题】:Using map() for columns in a pandas dataframe对 pandas 数据框中的列使用 map()
【发布时间】:2017-07-20 15:30:23
【问题描述】:

我的数据框中有一些列,我只想保留日期部分并删除时间部分。我已经列出了这些列:

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)

但这不起作用。我怎样才能做到这一点?

【问题讨论】:

    标签: python list pandas


    【解决方案1】:

    最简单的方法是使用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)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-06-24
        • 2017-10-23
        • 1970-01-01
        • 1970-01-01
        • 2022-08-14
        • 2018-08-04
        • 2015-01-19
        • 2020-05-26
        相关资源
        最近更新 更多