I know that we can create a single string to np.datetime64 format such as:
a = np.datetime64('2020-01-01')
But what if we have a list with multiple strings of dates in it?
How are we able to apply the same np.datetime64 to convert all the elements inside into a datetime format? Apart from doing a for-loop perhaps.
When you have your string list, use it as a source to a Numpy array,
passing datetime64 as dtype. E.g.:
lst = ['2020-01-01', '2020-02-05', '2020-03-07' ]
a = np.array(lst, dtype='datetime64')
When you execute a (actually print this array in a notebook),
you will get:
array(['2020-01-01', '2020-02-05', '2020-03-07'], dtype='datetime64[D]')
As you can see, in this case the default precision is Day.
But you can pass the precision explicitely, e.g. b = np.array(lst, dtype='datetime64[s]').
Don't be misled by apostrophes surrounding each element in the above
printout, they are not strings. To check it, execute a[0] and
you will get:
numpy.datetime64('2020-01-01')
Using list comprehension:
strings_list= [...]
npdate_list = [np.datetime64(x) for x in strings_list]
Is there a specific reason for you to want to avoid a loop?
List comprehension is okay?
Related
This question already has answers here:
How do I parse a string to a float or int?
(32 answers)
Closed 6 months ago.
I have a list with the following entries. How can I remove the single quotes for each entries in the list? I need to find the minimum value in the list. When I used min function, result is wrong due to the single quotes in the list. I know the workaround will be, making a script to save the minimum at each loop. But is there any other way to remove the single quotes, which makes the process simpler?
['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']
The below list is derived from a text file having lot of strings and after using split only Iam getting the single quotes. Can I do something there to avoid the single quotes?
Thanks
You have an array of strings. You can use float or other variants to convert a string to numeric. And then you can call min function on the numeric list.
a= ['-406', '-140', '-141', '-66.', '-135', '-142', '-136','-0.01']
b = [float(i) for i in a]
# gives b as
[-406.0, -140.0, -141.0, -66.0, -135.0, -142.0, -136.0, -0.01]
c = min(b)
# c is
-406.0
The result is wrong because the values are strings, not because of the single quotes - those are just there in your output to signify that they're strings and lists.
You can convert the values to floats using float, and then use min on the result:
lowest_value = min(map(float, your_list))
map applies the float conversion to every element in the list, then min retrieves the lowest value from the returned iterator.
I have a variable which is a = '"[200.0', ' 100.0]"'. While trying to access individual element like a[0] = '"[200.0'
The data type of this I checked says tuple. This is not the format I can work on, hence I want to convert this to a simple list/array like the following format for ex:
a = [200.0,100.0] .So that a[0] = 200.0 which could be either float or int data type.
I have tried using literal_eval, eval but it keeps throwing an error. A workable solution would be really helpful. Any ideas for this?
You can do it with regex to clean the a string from unwanted characters and then split it by the , to be a list
import re
a = '"[200.0', ' 100.0]"'
a = [re.sub(r"""["'\[\] ]""", "",i) for i in a]
print(a)
Output
['200.0', '100.0']
OR if you want it to be from float type
a = [float(re.sub(r"""["'\[\] ]""", "",i)) for i in a]
print(a)
Output
[200.0, 100.0]
Just for fun, you could also try this:
my_list = eval(eval(",".join(a)))
Explanation:
",".join(a) produces a single string '"[200.0, 100.0]"'
Calling eval() on this strips away the outer single-quotes, producing "[200.0, 100.0]" (that's a string containing [ as the first character and ] as the last)
Calling eval() again on this evaluates the above string, producing [200.0, 100.0], which gets assigned to my_list as a proper list object
I have a python list, like so:
list = [('array_1','array_2'),('array_1','array_3'),('array_2','array_3')]
The pairs in the list above are actually named numpy arrays, so I want to remove the quotes around each array name so that I'm left with:
list = [(array_1, array_2), (array_1, array_3), (array_2, array_3)]
How do I go about doing this?
Now you lst will contain actual NumPy arrays instead of just strings.
lst = [("array_1", "array_2"), ("array_1", "array_3"), ("array_2", "array_3")]
lst = [(globals()[i], globals()[j]) for i, j in lst]
This will output the numpy array (like array_1):
# str will be like : 'array_1'
globals()[str]
or
eval(str)
Note :
But I recommend to create a dictionary with keys as the strings and values as the corresponding arrays instead of eval and globals()
like this:
dict_ = {'array_1': array_1, 'array_2': array_2, 'array_3': array_3}
And use this dictionary wherever you want to access the variable
I want to convert a list of datetime objects into strings, but am confused on how to accomplish this task.
hm=dt.date(2013,1,2)
t=hm.strftime('%m/%d/%Y')
t
This produces : '01/02/2013'
However, when I change up the variable to be a list of dates as so, it throws off an error.
hm=[dt.date(2013,1,1), dt.date(2013,1,2)]
t=hm.strftime('%m/%d/%Y')
t
Error: list indices must be integers or slices, not datetime.date
Do I need to use some sort of for loop to accomplish this task?
You need to iterate over the list to convert each individual date into a string:
>>> t = [d.strftime('%m/%d/%Y') for d in hm]
Or if you want a string with all dates converted to a string concatenated by some other string (let's say ,) you can also do as:
>>> s = ', '.join(t)
If you want to solve this problem with a "conventional" for loop you can use:
import datetime as dt
hm = [dt.date(2013, 1, 1), dt.date(2013, 1, 2)]
t = []
for date in hm:
t.append(date.strftime('%m/%d/%Y'))
Otherwise the answer posted by dcg would be a cleaner and much better method.
I have a string
s='0xbb06e6cf,0xbb6fceb1,0xbabb39c3'
and first I want to convert it to array like
arr = [0xbb06e6cf,0xbb6fceb1,0xbabb39c3]
and then change the arr to float64 arr, which is the fastest way to convert the hex arr to float64?
You can do it using below code:
s='0xbb06e6cf,0xbb6fceb1,0xbabb39c3'
x=s.split(",")
print x
Output is:
['0xbb06e6cf', '0xbb6fceb1', '0xbabb39c3']
First you want to split the string on "," characters. Python implements a split() function that does this. Then you would want to convert each string returned from the split function into a number, you can use the int() function for this by specifying the base the number is in. Using list comprehension, the following code will do what you want:
s='0xbb06e6cf,0xbb6fceb1,0xbabb39c3'
arr = [int(n, base=16) for n in s.split(',')]