且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

获取Pandas数据帧中所选值的行和列标签

更新时间:2023-12-03 16:18:58

使用 np.where 获取True值的序数索引:

Use np.where to obtain the ordinal indices of the True values:

import numpy as np
import pandas as pd
df = pd.DataFrame(np.arange(16).reshape(4, 4), 
                  columns=pd.MultiIndex.from_product((('a', 'b'), ('x', 'y'))))

mask = (df % 6 == 0)
i, j = np.where(mask)
print(list(zip(df.index[i], df.columns[j])))

收益率

[(0, ('a', 'x')), (1, ('b', 'x')), (3, ('a', 'x'))]