将字典键映射到Python中的数据帧值

时间:2018-01-16 07:28:30

标签: python dictionary

我有一个矩阵如图所示:

Y = {'t': 5, 'r': 4, 'v': 2}

我有一个带键值对的字典,如下所示:

def mutation(pm):
    sum_mut = int(round(pm*total))
    i = 0
    while i < sum_mut:
        mut_row = int(random.random()*total)
        mut_col = int(random.random()*2393)
        offspring[mut_col][mut_row] ^= 1  
        i = i + 1
mutation(0.05)
print offspring

我试图将Y的值映射到矩阵X的每一列,这样如果Y中的值大于或等于X中的值,我们得到&#39; 1&#39;否则我们得到&#39; 0&#39;。

例如:在上面的代码中,输出应为:

Z = [011,001,011,110,001,111,111,100,111,011]

在此,对于第一行,&#39; t&#39; = 4&lt;在X中&#39; t&#39; = 5; &#39; r&#39; = 7&gt; &#39; R&#39; = 4; &#39; v&#39; = 3&gt; &#39; v&#39; = 2,所以我们得到011,依此类推。 我经历了thisthis,但无法获得我正在寻找的解决方案。 TIA。

2 个答案:

答案 0 :(得分:1)

ge使用带astype的投射蒙版整数:

df = df.ge(Y).astype(int)
print (df)
   t  r  v
a  0  1  1
b  0  0  1
c  0  1  1
d  1  1  0
e  0  0  1
f  1  1  1
g  1  1  1
h  1  0  0
i  1  1  1
j  0  1  1

如果希望输出list首先转换为str,然后再转换为join每行:

L = df.ge(Y).astype(int).astype(str).apply(''.join, axis=1).tolist()
print (L)
['011', '001', '011', '110', '001', '111', '111', '100', '111', '011']

或新专栏Z

df['Z'] = df.ge(Y).astype(int).astype(str).apply(''.join, axis=1)
print (df)
   t  r  v    Z
a  4  7  3  011
b  0  1  8  001
c  0  7  9  011
d  9  6  0  110
e  1  3  4  001
f  8  7  2  111
g  5  7  4  111
h  5  1  0  100
i  9  8  6  111
j  4  6  7  011

详情:

print (df.ge(Y))
       t      r      v
a  False   True   True
b  False  False   True
c  False   True   True
d   True   True  False
e  False  False   True
f   True   True   True
g   True   True   True
h   True  False  False
i   True   True   True
j  False   True   True

答案 1 :(得分:1)

在pandas中使用zip和列提取

keys = ["t", "r", "v"]

ans = zip(*[np.array(X[key] >= y[key]) for key in keys])

这将为您提供所需的输出,但数据类型为bool,可以转换为int

相关问题