【问题标题】:return 2 values from a function for two different columns with pandas in python在python中使用pandas从两个不同列的函数中返回2个值
【发布时间】:2021-05-05 19:19:01
【问题描述】:

我已经将一个函数应用于我的数据框的一列,该列包含带有年、月、日和小时、分钟、秒的日期,我想要做的是分开年、月、日并把它在一列中和时分秒同时放到另一列中,我的代码是这样的

def change_format(day):
  if day != 'nan':  
    format_1 = datetime.strptime(day, "%a %b %d %H:%M:%S %z  %Y")

    new_day = format_1.strftime('%d/%m/%Y')
    new_time = format_1.strftime('%H:%M:%S')                               
  return new_day,new_time
concatenar['pubDate']=concatenar['pubDate'].apply(change_format) 

到目前为止,在我的专栏中它没有返回任何值

【问题讨论】:

    标签: python pandas


    【解决方案1】:

    您可以使用.tolist() 将您的元组输出转换为列表,然后使用pd.DataFrame() 构造具有2 个必需列的数据框,如下所示:

    concatenar[["pubDate_date","pubDate_time"]] = pd.DataFrame(concatenar["pubDate"].apply(change_format).tolist(), index=concatenar.index)
    

    使用pd.DataFrame()pd.Series() 快得多。使用pd.DataFrame()pd.Series()建新列的速度对比可以参考其他一些帖子的this answerthis answer

    【讨论】:

      【解决方案2】:

      根据您的代码,不清楚您希望第二列的位置。您当前的 apply 函数应该返回一个列,其中每个条目都是一个元组。要将其解压缩成两列,您必须指定要放置输出的两列,并且可以通过 pd.Series() 再次使用 apply()。

      concatenar[ ["pubDate_day","pubDate_time"] ] = concatenar["pubDate"].apply(change_format).apply(pd.Series)
      

      您可以阅读更多关于解包元组列here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-04-02
        • 2021-05-09
        • 2016-06-19
        • 2018-06-06
        • 1970-01-01
        • 2020-05-03
        • 1970-01-01
        • 2020-01-17
        相关资源
        最近更新 更多