I have a list of tuples like this:
JavaScript
x
5
1
[
2
(12, Timestamp( ), 'test_1'),
3
(14, Timestamp( ), 'test_2')
4
]
5
What I do is:
JavaScript
1
9
1
temp_array = df.to_numpy()
2
3
for i, (cols) in enumerate(temp_array):
4
for val in cols:
5
if type(val) == pd.Timestamp:
6
val = np.datetime64(val)
7
8
tuples = [tuple(x) for x in temp_array]
9
How can I do to change directly the Timestamp type in this list of tuples ? More precisely, if type is pd.Timestamp I would like to change it to np.datetime64.
Advertisement
Answer
This is an example that should explain what you are missing.
JavaScript
1
14
14
1
my_list = [
2
['12', 123, 'test_1'],
3
['14', 456, 'test_2']
4
]
5
6
print(my_list)
7
8
for i, cols in enumerate(my_list):
9
for j, val in enumerate(cols):
10
if type(val) == int:
11
my_list[i][j] = str(val)
12
13
print(my_list)
14
The result:
[[’12’, 123, ‘test_1′], [’14’, 456, ‘test_2’]]
[[’12’, ‘123’, ‘test_1′], [’14’, ‘456’, ‘test_2’]]
So the complete answer is: don’t change tuples and use indexes to change the content of your list.
But I would create a new list and not change the existing one. Something like this:
JavaScript
1
11
11
1
my_list = [
2
['12', 123, 'test_1'],
3
['14', 456, 'test_2']
4
]
5
6
print(my_list)
7
8
new_list = [[str(item) if type(item) == int else item for item in cols] for cols in my_list]
9
10
print(new_list)
11