在python字典中提取计数为0的元素

时间:2019-11-08 08:33:59

标签: python dictionary

这是数据框代码:

    import pandas as pd
    storage = pd.DataFrame({'red_wire':[2,2,8,1,5],'white_wire':[5,5,3,5,2],'black_wire':[0,10,4,2,1]})

以及带有数据的数据框结构:

            red_wire  white_wire  black_wire
    0         2           5           0
    1         2           5          10
    2         8           3           4
    3         1           5           2
    4         5           2           1

考虑一下,我们有两个字典。它们外面有标签,标签的颜色必须在包装盒内:

    box1 = {'red_wire':2,'white_wire':5,'black_wire':10}
    box2 = {'red_wire':2,'white_wire':5,'black_wire':0}

我制作了此代码来打印包装盒中的物品,我的目的是控制和打印电汇代码,某些包装盒可能具有不同的颜色标签。 这就是为什么我使用以下代码:

    for key,value in box1.items():  #getting box tags and quantities

        col_name = [column for column in storage.columns if key == column] #columns in storage df

        for x,i in zip(storage.columns,storage.index): #accesing data in dataframe

            if x in col_name and value:

                print(x,col_name,value)

输出为:

red_wire ['red_wire'] 2
white_wire ['white_wire'] 5
black_wire ['black_wire'] 10        

调用box2:

for key,value in box2.items():

    col_name = [column for column in storage.columns if key == column]#columns in dict  

    for x,i in zip(storage.columns,storage.index):#accesing data in dataframe

        if x in col_name and value:

            print(x,col_name,value)

red_wire ['red_wire'] 2
white_wire ['white_wire'] 5             

在box2中,我期望将black_wire ['black_wire']设为0,但它假定它是一个可以跳过的值。 我想在字典评估中获得0篇文章的印刷品,并且如果包装盒中没有标签,则仅跳过值。

一些用户为我提供了很好的解决方案,使条件语句后的0带有“ not not None”:

 if x in col_name and value is not None:

它打印:

    red_wire ['red_wire'] 2
    white_wire ['white_wire'] 5
    black_wire ['black_wire'] 0

但是如果我特别问0:

for key,value in box2.items():

col_name = [column for column in storage.columns if key == column]#columns in dict  

for x,i in zip(storage.columns,storage.index):#accesing data in dataframe

    if x in col_name and value == storage[x][i]:

            print(x,col_name,value)

它打印:

red_wire ['red_wire'] 2
white_wire ['white_wire'] 5

“不是None”,没有任何区别

#is not None 1st
if x in col_name and value is not None and value == storage[x][i]:
            print(x,col_name,value)


red_wire ['red_wire'] 2
white_wire ['white_wire'] 5

#is not None after
if x in col_name and value == storage[x][i] and value is not None:

            print(x,col_name,value)


red_wire ['red_wire'] 2
white_wire ['white_wire'] 5

1 个答案:

答案 0 :(得分:2)

您的源代码中有2个问题。

0是有效值

在第一个版本中,您在条件语句中使用了value,就像注释中所说的bool(0) == false,因此您添加了指定is not None来管理存在0值的事实,根本没有价值。

列和值索引混合

在最终版本中,您将使用称为i的熊猫索引系统在循环中遍历列:

  

对于zip中的x,i(存储。列,存储。索引):#访问数据帧中的数据

但是您可以使用此索引在相应的数据框中查找值:

  

value == storage [x] [i]

很幸运,它适用于red_wirewhite_wire,甚至black_wire适用于box1

也许您想确保该值属于相应的Dataframe部分;在这种情况下,您可以通过以下方式更改源代码:

  

存储中的值[x] .values

这样,您根本就不需要检查值是否为None;并且您不需要在index中进行迭代;您的源代码可以简化为:

for x in storage.columns: if x in col_name and value in storage[x].values:

让我知道它是否满足您的需求。