Replace all Trues in a boolean dataframe with index valule

☆樱花仙子☆ 提交于 2021-01-29 02:05:20

问题


How can I replace all cells in a boolean dataframe (True/False) with the index name of that cell, when "True"? For example:

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

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

comes out as:

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

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

回答1:


Use df.mask:

Replace values where the condition is True.

df.mask(df,df.index)

         a      b
abc  False    abc
def    def  False


来源:https://stackoverflow.com/questions/60703065/replace-all-trues-in-a-boolean-dataframe-with-index-valule

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!