Reputation: 585
I have a list that has the data types of a dataframe. I would like to change the values in the list based on the existing values.
list = [dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('int64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64'), dtype('float64')]
I want a new list whose values are "Double" for values "dtype('float64')" and "Long" for anything else. I tried this expression but doesn't work.
listnew = ["Double" if x == "dtype('float64')" else "Long" for x in list]
Upvotes: 0
Views: 48
Reputation: 1443
Try the following:
import numpy as np
list_ = [np.dtype(np.int64) for n in range(18)] + [np.dtype(np.float64) for n in range(6)]
listnew = ["Double" if np.dtype(x) == np.dtype(np.float64) else "Long" for x in list_]
print(listnew)
Where
list_ = [np.dtype(np.int64) for n in range(18)] + [np.dtype(np.float64) for n in range(6)]
is equivalent to your given list:
list_ = [np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.int64), np.dtype(np.int64), np.dtype(np.int64), \
np.dtype(np.float64), np.dtype(np.float64), np.dtype(np.float64), \
np.dtype(np.float64), np.dtype(np.float64), np.dtype(np.float64)]
And the output when printing listnew
is the following list:
['Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Long', 'Double', 'Double', 'Double', 'Double', 'Double', 'Double']
Upvotes: 1