-2

I have the following structure:

list_of_tuples = [['portugal', np.nan, 'japan'], [np.nan, 'germany', 'canada'], ['UK', 'US', np.nan]] 

I want to change the numpy nan values for MissingValue and turning back to a list of tuples:

final_structure = [('portugal', 'MissingValue', 'japan'), ('MissingValue', 'germany', 'canada'), ('UK', 'US', 'MissingValue')] 

How can I replace the elements given a condition without iterating all over the elements? is there any single statement?

Javiss
  • 765
  • 3
  • 10
  • 24

2 Answers2

2

There is no way to do it without iterating because tuples are immutable. However, you can use list comprehension to create a new list of tuples within a single line, following

final_structure = [ tuple([ j if isinstance(j, str) else "MissingValue" for j in l ]) for l in list_of_tuples ]

In your specific case, you can replace everything that is not a string (the np.nan) by "MissingValue" using the intrinsic function isinstance().

Kefeng91
  • 802
  • 6
  • 10
1

This is one approach.

import numpy as np

list_of_tuples = [['portugal', np.nan, 'japan'], [np.nan, 'germany', 'canada'], ['UK', 'US', np.nan]]
list_of_tuples = map(lambda x: tuple(["MissingValue" if i is np.nan else i for i in x]), list_of_tuples)
print(list_of_tuples)

Output:

[('portugal', 'MissingValue', 'japan'), ('MissingValue', 'germany', 'canada'), ('UK', 'US', 'MissingValue')]
Rakesh
  • 81,458
  • 17
  • 76
  • 113