How to fill in missing values ​​with a tuple

consider df

 np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice([(1, 2), (3, 4), np.nan], (10, 10))) df 

enter image description here

how to populate those NaN using (0, 0) ?


I hacked this hack, but I guess there is a more direct way. And this does not work for pd.Series

 df.stack().unstack(fill_value=(0, 0)) 

enter image description here

+5
source share
2 answers

You can do with .applymap :

 import numpy as np import pandas as pd np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice([(1, 2), (3, 4), np.nan], (10, 10))) df.applymap(lambda x: (0,0) if x is np.nan else x) 

This will work for pd.Series if you use apply :

 df[0].apply(lambda x: (0, 0) if x is np.nan else x) 
+4
source

I like your workaround better than this, but it has to do its job.

 import pandas as pd import numpy as np np.random.seed([3,1415]) df = pd.DataFrame(np.random.choice([(1, 2), (3, 4), np.nan], (10, 10))) idx_arrays = np.where(df.isnull()) idx_tups = zip(idx_arrays[0], idx_arrays[1]) for tup in idx_tups: df.loc[tup] = (0, 0) 
+1
source

Source: https://habr.com/ru/post/1261301/


All Articles