Home > Back-end >  How to change data type in a list of tuples if this type is Timestamp?
How to change data type in a list of tuples if this type is Timestamp?

Time:10-15

I have a list of tuples like this:

[
(12, Timestamp(...), 'test_1'),
(14, Timestamp(...), 'test_2')
]

What I do is:

temp_array = df.to_numpy()

for i, (cols) in enumerate(temp_array):
    for val in cols:
        if type(val) == pd.Timestamp:
            val = np.datetime64(val)

tuples = [tuple(x) for x in temp_array]

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.

CodePudding user response:

This is an example that should explain what you are missing.

my_list = [
    ['12', 123, 'test_1'],
    ['14', 456, 'test_2']
]

print(my_list)

for i, cols in enumerate(my_list):
    for j, val in enumerate(cols):
        if type(val) == int:
            my_list[i][j] = str(val)

print(my_list)

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:

my_list = [
    ['12', 123, 'test_1'],
    ['14', 456, 'test_2']
]

print(my_list)

new_list = [[str(item) if type(item) == int else item for item in cols] for cols in my_list]

print(new_list)
  • Related