添加链接
link之家
链接快照平台
  • 输入网页链接,自动生成快照
  • 标签化管理网页链接
Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

I have a Pandas DataFrame with a column of time strings in hours and minutes (e.g. 1 hour 8 mins). Some cells are only minutes (e.g. 47 mins). I'm trying to convert from this format to just the integer value of the total number of minutes (e.g. 1 hour 8 mins would be 68).

I tried hard coding it but am having trouble with this as I am relatively new to Python. Is there a library that would be able to help me with this?

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

And when I use 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
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
                Would I have to use a for loop apply this to all? Sorry I'm very new to coding. Also where did the 'dt' and 'total_seconds' come from? Thanks!
– Heather
                Nov 4, 2016 at 0:20
                @Heather, no, you don't need any loops - pd.to_timedelta() is a "vectorized" function which will be applied on the whole series - see example in my answer. I've added a link to .dt.total_seconds() documentation...
– MaxU - stand with Ukraine
                Nov 4, 2016 at 0:24
                Thanks for the clarification. I seem to be getting a ValueError: unit abbreviation w/o a number.
– Heather
                Nov 4, 2016 at 16:53
                I forgot to mention that some cells have "error" in them instead of a time. Thank you again for your help!
– Heather
                Nov 4, 2016 at 17:11
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.