【问题标题】:How to fill true values of a dataframe with column names?如何用列名填充数据框的真实值?
【发布时间】:2018-02-06 19:20:21
【问题描述】:

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

A B C D 0 假 真 真 假 1 假 假 真 假 2 真 真 假 假

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

即得到结果为

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

【问题讨论】:

    标签: python pandas mask


    【解决方案1】:

    首先将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
    

    【讨论】:

    • df.astype(int).mask(df, df.columns, axis=1) 我应该猜吗?
    • 它返回给我ValueError: other must be the same shape as self when an ndarray
    • 另外,df.astype(int).where(~df, df.columns.to_series(), axis=1) 也可以。
    • 我使用0.20.3,python 3.5,windows 7
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-14
    • 2016-12-18
    • 1970-01-01
    • 2020-04-29
    • 2023-02-05
    相关资源
    最近更新 更多