Python: Do Not Exclude Rows After Map(dictionary)
I want to use a dictionary in order to create a new field/column in a dataframe. If the values don't match, I want the value to be set to 'NA' or something similar. So, I am using
Solution 1:
Several questions here:
(1) na_action
na_action
relates to the input not the output. Here is an example lifted from pandas
documentation:
>>> s = pd.Series([1, 2, 3, np.nan])
>>> s2 = s.map('this is a string {}'.format, na_action=None)
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 this is a string nan
dtype: object
>>> s3 = s.map('this is a string {}'.format, na_action='ignore')
0 this is a string 1.0
1 this is a string 2.0
2 this is a string 3.0
3 NaN
dtype: object
(2) How to keep rows if no match?
This may be what you are looking for. If it can't find a match, it won't change.
b = d.replace(dictionary)
(3) Print rows where Country_Code
does not have a match in dictionary.
df[~df['Country_Code'].isin(dictionary)]
Solution 2:
You can see the docs regarding the difference.
As for the desired result I suggest apply:
a = s.apply(lambda x: dictionary[x] if x in dictionary else x)
Post a Comment for "Python: Do Not Exclude Rows After Map(dictionary)"