用索引值替换布尔数据框中的所有真值 [英] Replace all Trues in a boolean dataframe with index valule
本文介绍了用索引值替换布尔数据框中的所有真值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当真"时,如何用该单元格的索引名称替换布尔数据帧(真/假)中的所有单元格?例如:
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")
)
结果为:
df = pd.DataFrame(
[
[False, abc],
[def, False],
],
index=["abc", "def"],
columns=list("ab")
)
推荐答案
使用 df.mask
:
替换条件为 True 的值.
Replace values where the condition is True.
df.mask(df,df.index)
<小时>
a b
abc False abc
def def False
这篇关于用索引值替换布尔数据框中的所有真值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文