【问题标题】:Create new binary variable based on multiple binary columns in other data frame with same index基于具有相同索引的其他数据框中的多个二进制列创建新的二进制变量
【发布时间】:2020-07-15 01:59:37
【问题描述】:

我有一个数据框,其中包含森林 i(第一列)和设施 j(顶行)之间的距离值(公里):

Df1=
Forest,Bell Bay,Surrey Hills,Smithton,Hobart
Coupe1,158,194,10,49
Coupe2,156,169,71,84
Coupe3,10,186,101,163
Coupe4,47,194,134,139
Coupe5,144,161,135,56
Coupe6,27,127,134,36
Coupe7,114,104,143,113
Coupe8,71,170,190,140
Coupe9,194,154,173,128
Coupe10,46,194,92,36

我有最大距离参数 Dmax = 100 公里

我创建了一个带有二进制值的数据框。如果森林与设施之间的距离

Df2=
Forest,Bell Bay,Surrey Hills,Smithton,Hobart
Coupe1,0,0,1,1
Coupe2,0,0,1,1
Coupe3,1,0,0,0
Coupe4,1,0,0,0
Coupe5,0,0,0,1
Coupe6,1,0,0,1
Coupe7,0,0,0,0
Coupe8,1,0,0,0
Coupe9,0,0,0,0
Coupe10,1,0,1,1

我有另一个数据框,其供应浮点值如下所示:(请注意,森林或索引是相同的)

Df3=
Forest,Supply
Coupe1,6000
Coupe2,1000
Coupe3,9000
Coupe4,3000
Coupe5,3000
Coupe6,4000
Coupe7,9000
Coupe8,7000
Coupe9,5000
Coupe10,3000

我想用二进制参数创建另一个数据框(或前一个数据框 ['Binary'] 中的额外列),如果森林 i 在 任何设施 j 的 Dmax 内,则为 1。数据框应如下所示:

Df3=
Forest,Supply, Binary
Coupe1,6000,1
Coupe2,1000,1
Coupe3,9000,1
Coupe4,3000,1
Coupe5,3000,1
Coupe6,4000,1
Coupe7,9000,0
Coupe8,7000,1
Coupe9,5000,0
Coupe10,3000,1

请注意,对于 Coupe 7 和 9,二进制数为 0,因为根据第一个数据框,这两个森林距离贝尔湾、萨里山、史密斯顿、霍巴特设施都超过 100 公里。 最好的表达方式是什么?

如果Forest行中有1,则Df3['Binary'] =1,否则为0

例如。

for i in Df2
if Coupe1,0,0,1,1 
then 1 in Df3['Binary']

if Couple7, 0,0,0,0 
then 0 in Df3['Binary']

【问题讨论】:

    标签: python arrays pandas numpy dataframe


    【解决方案1】:

    由于Df2Df3 具有相同的行序列,您可以这样做:

    Df3['binary'] = Df2.iloc[:,1:].sum(1).gt(0)*1
    

    如果Df2Df3中的行顺序不同,你可以这样做:

    Df3['binary'] = Df3['Forest'].map(Df2.set_index('Forest').sum(1).gt(0)*1)
    

    【讨论】:

    • 我对同一行 df 尝试了以下操作:df3['Binary'] = df2.iloc[:,0:len(df2.columns)].max(axis=1)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-06
    • 2021-12-22
    • 1970-01-01
    • 2021-04-19
    • 1970-01-01
    相关资源
    最近更新 更多