【问题标题】:How to use apply function on multiple columns at once如何一次在多列上使用应用功能
【发布时间】:2018-09-26 13:15:53
【问题描述】:

是否可以在 pandas 中的多个列上调用 apply 函数,如果可以,如何做到这一点..例如,

 df['Duration'] = df['Hours', 'Mins', 'Secs'].apply(lambda x,y,z: timedelta(hours=x, minutes=y, seconds=z))

This is what the expected output should look like once everything comes together

谢谢。

【问题讨论】:

    标签: python pandas apply duration timedelta


    【解决方案1】:

    你应该使用:

    df['Duration'] = pd.to_timedelta(df.Hours*3600 + df.Mins*60 + df.Secs, unit='s')
    

    当您在 DataFrameaxis=1 上使用 apply 时,这是一个行计算,所以通常这种语法是有意义的:

    df['Duration'] = df.apply(lambda row: pd.Timedelta(hours=row.Hours, minutes=row.Mins, 
        seconds=row.Secs), axis=1)
    

    一些时间

    import pandas as pd
    import numpy as np
    df = pd.DataFrame({'Hours': np.tile([1,2,3,4],50),
                      'Mins':  np.tile([10,20,30,40],50),
                      'Secs': np.tile([11,21,31,41],50)})
    
    %timeit pd.to_timedelta(df.Hours*3600 + df.Mins*60 + df.Secs, unit='s')
    #432 µs ± 5.4 µs per loop (mean ± std. dev. of 7 runs, 1000 loops each)
    
    %timeit df.apply(lambda row: pd.Timedelta(hours=row.Hours, minutes=row.Mins, seconds=row.Secs), axis=1)
    #12 ms ± 67.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
    

    与往常一样,申请应该是最后的手段。

    【讨论】:

    • 您好,我尝试了您的解决方案,但我不断收到此错误:() got an unexpected keyword argument 'axis'
    • @Blank 您需要确保您实际上在DataFrame 上使用apply 而不是SeriesSeries.apply() 没有轴参数,这可能是导致该错误的原因 Series apply
    • 但同样,不要在这里使用 apply 方法。对于较大的 DataFrame,它非常慢。
    • 好的,第一行代码是你提出的主要建议吗?另外,为什么要乘以 3600? cus 当我使用第一行时出现以下错误: int too big to convert
    • 在我看来,你有一个 DataFrame 有 3 列 HoursMinsSecs,它们都是整数。我以秒为单位计算总时间,然后使用 pd.to_timedelta 以秒为单位。但似乎这不是你所拥有的。您应该使用 print(df) 发布您的数据,这样我们才能真正帮助您了解您真正拥有的东西。
    【解决方案2】:

    在带有axis=1 的数据帧上使用apply https://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.apply.html

    triangles = [{ 'base': 20, 'height': 9 }, { 'base': 10, 'height': 7 }, { 'base': 40, 'height': 4 }]

    triangles_df = pd.DataFrame(triangles)

    def calculate_area(row): return row['base'] * row['height'] * 0.5

    triangles_df.apply(calculate_area, axis=1)

    祝你好运!

    【讨论】:

      【解决方案3】:

      这可能会有所帮助。

      import pandas as pd
      import datetime as DT
      df = pd.DataFrame({"Hours": [1], "Mins": [2], "Secs": [10]})
      df = df.astype(int)
      
      df['Duration'] = df[['Hours', 'Mins', 'Secs']].apply(lambda x: DT.timedelta(hours=x[0], minutes=x[1], seconds=x[2]), axis=1)
      
      print(df)
      print(df["Duration"])
      

      输出:

         Hours  Mins  Secs  Duration
      0      1     2    10  01:02:10
      
      0   01:02:10
      dtype: timedelta64[ns]
      

      【讨论】:

      • 这当然很有帮助,但我收到了这个错误:('index out of bounds', 'occured at index 0')
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-14
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多