【发布时间】:2022-01-04 19:56:24
【问题描述】:
我有一个看起来像这样的数据框:
df = pd.DataFrame(np.random.rand(10,3), columns = ['col1', 'col2', 'col3'])
| col1 | col2 | col3 | |
|---|---|---|---|
| 0 | 0.692154 | 0.286560 | 0.515904 |
| 1 | 0.798917 | 0.777593 | 0.971300 |
我还有另一个矩阵,它是一个看起来像这样的布尔矩阵:
b_matrix = pd.DataFrame(np.array([[0,1,1],
[1,1,0],
[0,0,1],
[0,1,0]]),
columns = ['col1', 'col2', 'col3'],
index = ['input1', 'input2', 'input3', 'input4'])
| col1 | col2 | col3 | |
|---|---|---|---|
| input1 | 0 | 1 | 1 |
| input2 | 1 | 1 | 0 |
| input3 | 0 | 0 | 1 |
| input4 | 0 | 1 | 0 |
所以这里的想法是我将提供一些输入,这将与b_matrix 进行检查,然后我将只返回df 的相应列。例如如果输入为input1,则输出为df[['col2', 'col3']]:
| col2 | col3 | |
|---|---|---|
| 0 | 0.286560 | 0.515904 |
| 1 | 0.777593 | 0.971300 |
我可以想办法做到这一点,保留列名的静态列表以每次检查,但我想知道是否有更直接的方法?
【问题讨论】:
标签: python pandas numpy boolean