简体   繁体   中英

Mask dataframe with another multi-indexed Series

I have a Dataframe that I would like to mask (convert to NaN) with the boolean values of a multi-indexed Series where the multi-index of the Series are also the column names in the Dataframe. For example, if df is:

df = pd.DataFrame({ 'A': (188, 750, 1330, 1385, 188, 750, 810, 1330, 1385),
                     'B': (1, 2, 4, 5, 1, 2, 3, 4, 5),
                     'C': (2, 5, 7, 2, 5, 5, 3, 7, 2),
                     'D': ('foo', 'foo', 'foo', 'foo', 'bar', 'bar', 'bar', 'bar', 'bar') })

    A    B  C   D
0   188  1  2   foo
1   750  2  5   foo
2   1330 4  7   foo
3   1385 5  2   foo
4   188  1  5   bar
5   750  2  5   bar
6   810  3  3   bar
7   1330 4  7   bar
8   1385 5  2   bar

and the multi-indexed Series ser is:

arrays = [('188', '750', '810', '1330', '1385'),
          ('1', '2', '3', '4', '5')]
tuples = list(zip(*arrays))
index = pd.MultiIndex.from_tuples(tuples, names=['A', 'B'])
ser = pd.Series([False, False, True, False, True], index=index)

A     B
188   1    False
750   2    False
810   3    True
1330  4    False
1385  5    True
dtype: bool

how can I mask (convert to NaN) the value on column C in df where the entries are False in the Series ser , in order to end with a final Dataframe that would look like:

    A    B  C   D
0   188  1  2   foo
1   750  2  5   foo
2   1330 4  7   foo
3   1385 5  NaN foo
4   188  1  5   bar
5   750  2  5   bar
6   810  3  NaN bar
7   1330 4  7   bar
8   1385 5  NaN bar

Change the initialization step for ser :

arrays = [('188', '750', '810', '1330', '1385'),
          ('1', '2', '3', '4', '5')]
# Note: The change is in this step - make the levels numeric.
tuples = list(zip(*map(pd.to_numeric, arrays)))
index = pd.MultiIndex.from_tuples(tuples, names=['A', 'B'])
ser = pd.Series([False, False, True, False, True], index=index)

Initialize index 's levels to have the same dtype as 'A' and 'B'. Hopefully, this shouldn't be an issue.

This will let us build a much simpler solution using loc and index-based selection and assignment.

u = df.set_index(['A', 'B'])
u.loc[ser.index[ser], 'C'] = np.nan

u.reset_index()
      A  B    C    D
0   188  1  2.0  foo
1   750  2  5.0  foo
2  1330  4  7.0  foo
3  1385  5  NaN  foo
4   188  1  5.0  bar
5   750  2  5.0  bar
6   810  3  NaN  bar
7  1330  4  7.0  bar
8  1385  5  NaN  bar

If you're faced with a situation where you are given ser and need to change the dtype of the index, you can quickly re-build it using a list comprehension inside pd.Index.set_levels .

ser.index = ser.index.set_levels([l.astype(int) for l in ser.index.levels]) 
# Alternative,
# ser.index = ser.index.set_levels([
#     pd.to_numeric(l) for l in ser.index.levels]) 

Now, this works:

u = df.set_index(['A', 'B'])
u.loc[ser.index[ser], 'C'] = np.nan

u.reset_index()

      A  B    C    D
0   188  1  2.0  foo
1   750  2  5.0  foo
2  1330  4  7.0  foo
3  1385  5  NaN  foo
4   188  1  5.0  bar
5   750  2  5.0  bar
6   810  3  NaN  bar
7  1330  4  7.0  bar
8  1385  5  NaN  bar

Note the ser.index[ser] indexing step in loc , we use ser 's index instead of index directly.

Use:

# Converting ser to a dataframe 
ndf = pd.DataFrame(ser).reset_index()

# Fetching B values against which C values needs to be mapped to NaN
idx = ndf[ndf.iloc[:,2] == True].B.values

# Fetching df index where C values needs to be mapped to NaN
idx_ = df[df.B.isin(idx)].index

# Mapping of C values to NaN
df.loc[idx_,'C'] = np.NaN


+---+------+---+-----+-----+
|   |   A  | B |  C  |  D  |
+---+------+---+-----+-----+
| 0 |  188 | 1 | 2.0 | foo |
| 1 |  750 | 2 | 5.0 | foo |
| 2 | 1330 | 4 | 7.0 | foo |
| 3 | 1385 | 5 | NaN | foo |
| 4 |  188 | 1 | 5.0 | bar |
| 5 |  750 | 2 | 5.0 | bar |
| 6 |  810 | 3 | NaN | bar |
| 7 | 1330 | 4 | 7.0 | bar |
| 8 | 1385 | 5 | NaN | bar |
+---+------+---+-----+-----+

Use isin for check membership between both MultiIndex :

#convert columns to strings for same types of levels
df[['A','B']] = df[['A','B']].astype(str)
df.loc[df.set_index(['A','B']).index.isin(ser.index[ser]), 'C'] = np.nan
print (df)
      A  B    C    D
0   188  1  2.0  foo
1   750  2  5.0  foo
2  1330  4  7.0  foo
3  1385  5  NaN  foo
4   188  1  5.0  bar
5   750  2  5.0  bar
6   810  3  NaN  bar
7  1330  4  7.0  bar
8  1385  5  NaN  bar

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM