0

I have data in a list. And it is in the form of milliseconds.

datas = [
    '0m0.201s', '0m0.147s', '0m0.140s', '0m0.204s', '0m0.204s', '0m0.225s', 
    '0m0.189s', '0m0.205s', '0m0.204s', '0m0.205s', '0m0.176s', '0m0.184s', 
    '0m0.188s', '0m0.191s', '0m0.208s', '0m0.200s', '0m0.200s', '0m0.200s',
    '0m0.200s', '0m0.180s', '0m0.193s', '0m0.200s', '0m0.211s', '0m0.189s', 
    '0m0.191s', '0m0.240s', '0m0.208s', '0m0.236s'
]

I have tried to first convert it into seconds to calculate the average. But I can't the get the way to do so.

How can I find the average of this data in python?

Vincent Bénet
  • 1,212
  • 6
  • 20
  • 1
    You have values in miliseconds, you can iterate over each element, remove `m` and `s` from elements as those wouldnt not change the value when all elements are in mili seconds, then you can use `sum` to find sum of array and `len` to count number of arrays. When you then divide `sum/len`, you get mean. – Bijay Regmi Mar 25 '21 at 16:02
  • 1
    You can convert your values to a timedelta ([how to](https://stackoverflow.com/questions/4628122/how-to-construct-a-timedelta-object-from-a-simple-string)), and then either sum them like [here](https://stackoverflow.com/questions/18860821/adding-together-timedeltas-in-python) or use pandas like [here](https://stackoverflow.com/questions/19681703/average-time-for-datetime-list). – Thymen Mar 25 '21 at 16:08

1 Answers1

0

Since your values are in miliseconds, we can remove letters m and s without changing the value of each element. For that we are going to use regex.

import re

L=['0m0.201s', '0m0.147s', '0m0.140s', '0m0.204s', '0m0.204s', '0m0.225s', '0m0.189s', '0m0.205s', '0m0.204s', '0m0.205s', '0m0.176s', '0m0.184s', '0m0.188s', '0m0.191s', '0m0.208s', '0m0.200s', '0m0.200s', '0m0.200s', '0m0.200s', '0m0.180s', '0m0.193s', '0m0.200s', '0m0.211s', '0m0.189s', '0m0.191s', '0m0.240s', '0m0.208s', '0m0.236s']

float_array = [float(re.sub("[a-z]","",x)) for x in L] #replacing m&s and converting each element to floating number

mean = sum(float_array)/len(float_array) #your mean

Alternatively you can use average function from statistics package.

Bijay Regmi
  • 1,187
  • 2
  • 11
  • 25