【问题标题】:Generating boolean dataframe based on contents in series and dataframe根据系列内容和数据框生成布尔数据框
【发布时间】:2020-06-01 05:45:47
【问题描述】:

我有:

 df = pd.DataFrame(
        [
            [22, 33, 44],
            [55, 11, 22],
            [33, 55, 11],
        ],
        index=["abc", "def", "ghi"],
        columns=list("abc")
    ) # size(3,3)

和:

unique = pd.Series([11, 22, 33, 44, 55]) # size(1,5)

然后我根据uniquedf 创建一个新的df,这样:

df_new = pd.DataFrame(index=unique, columns=df.columns) # size(5,3)

从这个新创建的df中,我想基于uniquedf创建一个新的布尔df,所以最终结果是:

 df_new = pd.DataFrame(
        [
            [0, 1, 1],
            [1, 0, 1],
            [1, 1, 0],
            [0, 0, 1],
            [1, 1, 0],
        ],
        index=unique,
        columns=df.columns
    ) 

这个新的 df 是真还是假,这取决于该值是否存在于原始数据帧中。例如,第一列有三个值:[22,55,33]。在尺寸为 (5,3) 的 df 中,第一列将是:[0, 1, 1, 0, 1] 即 [0, 22, 33, 0 , 55]

我试过filter2 = unique.isin(df) 但这不起作用,也不是null。我尝试应用过滤器,但返回的尺寸不正确。我该怎么做?

【问题讨论】:

    标签: pandas dataframe boolean series


    【解决方案1】:

    DataFrame.stackDataFrame.reset_indexDataFrame.pivot 一起使用,然后通过DataFrame.notna 检查是否没有缺失值,将True->1False->0 映射转换为整数,最后通过DataFrame.rename_axis 删除索引和列名:

    df_new = (df.stack()
                .reset_index(name='v')
                .pivot('v','level_1','level_0')
                .notna()
                .astype(int)
                .rename_axis(index=None, columns=None))
    print (df_new)
        a  b  c
    11  0  1  1
    22  1  0  1
    33  1  1  0
    44  0  0  1
    55  1  1  0
    

    Helper Series 不是必需的,但如果有更多值或需要通过 helper Series 更改订单,请使用添加 DataFrame.reindex:

    #added 66
    unique = pd.Series([11, 22, 33, 44, 55,66])
    
    df_new = (df.stack()
                .reset_index(name='v')
                .pivot('v','level_1','level_0')
                .reindex(unique)
                .notna()
                .astype(int)
                .rename_axis(index=None, columns=None))
    print (df_new)
        a  b  c
    11  0  1  1
    22  1  0  1
    33  1  1  0
    44  0  0  1
    55  1  1  0
    66  0  0  0
    

    【讨论】:

    • 太棒了,正是我想要的。谢谢!
    猜你喜欢
    • 2019-07-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多