这是数据框代码:
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 篇文章的打印结果,并且仅在盒子上不存在标签时跳过值。
一些用户为我提供了很好的解决方案,可以在条件句后使用“is not None”得到 0:
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
最佳答案
您的源代码中有 2 个问题。
0 是有效值
在您的第一个版本中,您在条件中使用了 value
,并且如注释中所述,bool(0) == false
,因此您添加以指定 is not None
来管理存在 0 值且根本没有值的事实。
列和值索引混合
在最终版本中,您将使用 Panda 索引系统(在循环中称为 i
)对列进行迭代:
for x,i in zip(storage.columns,storage.index):#accesing data in dataframe
但是你使用这个索引来查找相应Dataframe中的值:
value == storage[x][i]
你很幸运,它适用于 red_wire
和 white_wire
,甚至适用于 box1
的 black_wire
。
也许你想确保该值属于相应的Dataframe部分;在这种情况下,您可以通过以下方式更改源代码:
value in storage[x].values
这样你根本不需要检查 value 是否为 None;并且您不需要在 index
中进行迭代;您的源代码可以简化为:
对于 storage.columns 中的 x:
如果 x 在 col_name 中且值在 storage[x].values 中:
如果它满足您的需求,请告诉我。
关于python - 提取Python字典中计数为0的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58763015/