用另一个多索引序列屏蔽数据帧

2024-04-16 09:59:12 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个数据帧,我想用一个多索引序列的布尔值来屏蔽(转换为NaN),其中序列的多索引也是数据帧中的列名。例如,如果df是:

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

多索引序列ser是:

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

如何屏蔽(转换为NaN)列C中的值,其中条目是序列ser中的False,以便以如下所示的最终数据帧结束:

    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

Tags: 数据falsetruedataframedfindexfoobar
3条回答

用途:

# 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 |
+ -+   + -+  -+  -+

使用^{}检查两个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

更改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)

初始化index的级别,使其具有与“A”和“B”相同的数据类型。希望这不是问题。你知道吗

这将让我们使用loc和基于索引的选择和分配来构建一个更简单的解决方案。你知道吗

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

如果您面临这样一种情况,即您得到了ser,并且需要更改索引的数据类型,那么您可以使用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]) 

现在,这是可行的:

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

注意ser.index[ser]索引步骤在loc中,我们直接使用ser的索引而不是index。你知道吗

相关问题 更多 >