na_if
In [1]:
Copied!
# https://dplyr.tidyverse.org/reference/na_if.html
%run nb_helpers.py
from datar.data import starwars
from datar.all import *
nb_header(na_if)
# https://dplyr.tidyverse.org/reference/na_if.html
%run nb_helpers.py
from datar.data import starwars
from datar.all import *
nb_header(na_if)
In [2]:
Copied!
na_if(range(5), list(range(4,-1,-1)))
na_if(range(5), list(range(4,-1,-1)))
Out[2]:
0 0.0 1 1.0 2 NaN 3 3.0 4 4.0 Name: x, dtype: float64
In [2]:
Copied!
x = tibble(x=[1, -1, 0, 10]).x
100 / x
x = tibble(x=[1, -1, 0, 10]).x
100 / x
Out[2]:
0 100.0 1 -100.0 2 inf 3 10.0 Name: x, dtype: float64
In [3]:
Copied!
na_if(x, 0)
na_if(x, 0)
Out[3]:
0 1.0 1 -1.0 2 NaN 3 10.0 Name: x, dtype: float64
In [4]:
Copied!
y = tibble(y=["abc", "def", "", "ghi"]).y
na_if(y, "")
y = tibble(y=["abc", "def", "", "ghi"]).y
na_if(y, "")
Out[4]:
0 abc 1 def 2 NaN 3 ghi Name: x, dtype: object
In [5]:
Copied!
starwars >> \
select(f.name, f.eye_color) >> \
mutate(eye_color = na_if(f.eye_color, "unknown"))
starwars >> \
select(f.name, f.eye_color) >> \
mutate(eye_color = na_if(f.eye_color, "unknown"))
Out[5]:
name | eye_color | |
---|---|---|
<object> | <object> | |
0 | Luke Skywalker | blue |
1 | C-3PO | yellow |
2 | R2-D2 | red |
3 | Darth Vader | yellow |
... | ... | ... |
4 | Leia Organa | brown |
82 | Rey | hazel |
83 | Poe Dameron | brown |
84 | BB8 | black |
85 | Captain Phasma | NaN |
86 | Padmé Amidala | brown |
87 rows × 2 columns
In [6]:
Copied!
starwars >> \
mutate(across(where(is_character), lambda x: na_if(x, "unknown")))
starwars >> \
mutate(across(where(is_character), lambda x: na_if(x, "unknown")))
Out[6]:
name | height | mass | hair_color | skin_color | eye_color | birth_year | sex | gender | homeworld | species | |
---|---|---|---|---|---|---|---|---|---|---|---|
<object> | <float64> | <float64> | <object> | <object> | <object> | <float64> | <object> | <object> | <object> | <object> | |
0 | Luke Skywalker | 172.0 | 77.0 | blond | fair | blue | 19.0 | male | masculine | Tatooine | Human |
1 | C-3PO | 167.0 | 75.0 | NaN | gold | yellow | 112.0 | none | masculine | Tatooine | Droid |
2 | R2-D2 | 96.0 | 32.0 | NaN | white, blue | red | 33.0 | none | masculine | Naboo | Droid |
3 | Darth Vader | 202.0 | 136.0 | none | white | yellow | 41.9 | male | masculine | Tatooine | Human |
... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... | ... |
4 | Leia Organa | 150.0 | 49.0 | brown | light | brown | 19.0 | female | feminine | Alderaan | Human |
82 | Rey | NaN | NaN | brown | light | hazel | NaN | female | feminine | NaN | Human |
83 | Poe Dameron | NaN | NaN | brown | light | brown | NaN | male | masculine | NaN | Human |
84 | BB8 | NaN | NaN | none | none | black | NaN | none | masculine | NaN | Droid |
85 | Captain Phasma | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN | NaN |
86 | Padmé Amidala | 165.0 | 45.0 | brown | light | brown | 46.0 | female | feminine | Naboo | Human |
87 rows × 11 columns
In [ ]:
Copied!