python - 如何用列名填充数据框的真实值?

标签 python pandas mask

我有一个包含 True 和 False 值的 DataFrame。

       A      B      C      D
0  False  True   True   False
1  False  False  True   False
2  True   True   False  False

我想用列名填充真值,用 0 填充假值。我该怎么做?

即得到结果为

   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

最佳答案

首先将booelan替换为int,然后使用maskwhere通过 ~ 反转掩码:

df = df.astype(int).mask(df, df.columns.to_series(), axis=1)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

df = df.astype(int).where(~df, df.columns.to_series(), axis=1)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

谢谢John Galt用于改进新版本的 pandas 0.21.x:

df = df.astype(int).mask(df, df.columns, axis=1)

numpy 解决方案:

a = np.tile(df.columns, [len(df.index),1])
print (a)
[['A' 'B' 'C' 'D']
 ['A' 'B' 'C' 'D']
 ['A' 'B' 'C' 'D']]

df = pd.DataFrame(np.where(df.astype(int), a, 0), columns=df.columns, index = df.index)
print (df)
   A  B  C  D
0  0  B  C  0
1  0  0  C  0
2  A  B  0  0

关于python - 如何用列名填充数据框的真实值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45937336/

相关文章:

python : email sending failing on SSL read

pandas - 将具有 nan 值的 str 类型字典转换为 dict 类型对象

python - 用函数的结果替换值

transparency - 如何在opencv-python中创建透明掩码

python - `Pandas argmax` 在屏蔽后获取所有 `True` 索引(Python 3)(例如 (pd.Series > 0).argmax()))

python - 如何获取箱线图中每个中位数的值?

python - Socket编程--发送和接收图像

python - 读取 SQL 文件并使用 Count Vectorizer 获取单词出现次数

css - 剪贴蒙版到 SVG

python - 注释掉并取消注释 xml 元素