【问题标题】:Converting from hours and minutes to total minutes in Python在 Python 中从小时和分钟转换为总分钟数
【发布时间】:2017-03-17 17:23:01
【问题描述】:

我有一个 Pandas DataFrame,其中有一列以小时和分钟为单位的时间字符串(例如 1 小时 8 分钟)。有些单元格只有几分钟(例如 47 分钟)。 我正在尝试从这种格式转换为总分钟数的整数值(例如 1 小时 8 分钟将是 68)。

我尝试对其进行硬编码,但由于我对 Python 比较陌生,因此遇到了麻烦。 有没有图书馆可以帮助我解决这个问题?

In [10]: df_times = pd.DataFrame(times)
         df_times.columns = ["times"]
         df_times
Out[10]:       times
        0      31 mins
        1      1 hour 28 mins
        2      1 hour 1 min
        3      1 min
        ...    ...
        22849  ERROR
        22850  7 mins


In [11]: (pd.to_timedelta(df_times["times"].str.replace('mins','min')).dt.total_seconds()//60).astype(int)
ValueError: unit abbreviation w/o a number

当我使用 errors="coerce" 时:

In [12]: (pd.to_timedelta(df_times["times"].str.replace('mins','min'), errors="coerce").dt.total_seconds()//60).astype(int)
ValueError: Cannot convert NA to integer

【问题讨论】:

    标签: python parsing pandas time dataframe


    【解决方案1】:

    您可以使用pandas.to_timedelta()Series.dt.total_seconds() 方法:

    In [244]: df
    Out[244]:
                      time
    0        1 hour 8 mins
    1              47 mins
    2  10 hours 12 minutes
    3                1 min
    
    In [245]: (pd.to_timedelta(df.time.str.replace('mins', 'min'))
         ...:    .dt.total_seconds()//60).astype(int)
         ...:
    Out[245]:
    0     68
    1     47
    2    612
    3      1
    Name: time, dtype: int32
    

    【讨论】:

    • 我是否必须使用 for 循环将此应用于所有?对不起,我对编码很陌生。 'dt' 和 'total_seconds' 又是从哪里来的呢?谢谢!
    • @Heather,不,您不需要任何循环 - pd.to_timedelta() 是一个“矢量化”函数,将应用于整个系列 - 请参阅我的答案中的示例。我添加了指向.dt.total_seconds() 文档的链接...
    • 感谢您的澄清。我似乎收到了 ValueError: unit abbreviation w/o a number。
    • @Heather,你能提供一个Minimal, Complete, and Verifiable example吗?
    • 我忘了提到某些单元格中有“错误”而不是时间。再次感谢您的帮助!
    猜你喜欢
    • 2019-02-22
    • 2021-02-22
    • 2019-01-05
    • 2015-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-28
    相关资源
    最近更新 更多