用索引值替换布尔数据框中的所有True

时间:2020-03-16 09:07:28

标签: python-3.x pandas replace

当“ True”为真时,如何用该单元格的索引名替换布尔数据框(True / False)中的所有单元格?例如:

df = pd.DataFrame(
    [
        [False, True],
        [True, False],

    ],
    index=["abc", "def"],
    columns=list("ab")
)

显示为:

df = pd.DataFrame(
    [
        [False, abc],
        [def, False],

    ],
    index=["abc", "def"],
    columns=list("ab")
)

1 个答案:

答案 0 :(得分:4)

使用df.mask

替换条件为True的值。

df.mask(df,df.index)

         a      b
abc  False    abc
def    def  False