Python 在Panda数据框中搜索值会返回不一致的结果
我试图在熊猫数据框中搜索匹配项。我发现结果不一致,或者我使用了错误的代码类型。我使用的是in命令,它并不总是一致的。如果我比较这些值(参见示例),它会起作用。指挥部有问题吗 代码示例:Python 在Panda数据框中搜索值会返回不一致的结果,python,pandas,dataframe,Python,Pandas,Dataframe,我试图在熊猫数据框中搜索匹配项。我发现结果不一致,或者我使用了错误的代码类型。我使用的是in命令,它并不总是一致的。如果我比较这些值(参见示例),它会起作用。指挥部有问题吗 代码示例: import pandas as pd report = pd.DataFrame(columns = (['col1','col2'])) report i = 0 while i < 100: a = str(i) addthis = pd.Series({'col1':a,'col2'
import pandas as pd
report = pd.DataFrame(columns = (['col1','col2']))
report
i = 0
while i < 100:
a = str(i)
addthis = pd.Series({'col1':a,'col2':'AG100'})
report = report.append(addthis,ignore_index=True)
i = i + 1
###this will find a match but not 100 of the time%
i = 0
while i < len(report):
if str(i) in str(report[0:len(report)]):
print('found match on ',i)
else:
print('No match found on ',i)
i = i + 1
###this will find a match 100of the time%
i = 0
while i < len(report):
if str(i) == report.ix[i,0]:
print('found match on ',i)
else:
print('No match found on ',i)
i = i + 1
将熊猫作为pd导入
report=pd.DataFrame(列=(['col1','col2']))
报告
i=0
当我<100时:
a=str(i)
addthis=pd.Series({'col1':a,'col2':'AG100'})
report=report.append(addthis,ignore_index=True)
i=i+1
###这将找到一个匹配项,但不是100%
i=0
而我(报告):
如果str(i)在str(报告[0:len(报告)])中:
打印('在上找到匹配项',i)
其他:
打印('i'上未找到匹配项)
i=i+1
###这将在100%的时间内找到匹配项
i=0
而我(报告):
如果str(i)=report.ix[i,0]:
打印('在上找到匹配项',i)
其他:
打印('i'上未找到匹配项)
i=i+1
您正在遇到问题,因为您正在将数据帧的部分转换为字符串。如果您查看使用str(report[0:len(report)])
时打印出来的内容,您会发现它不仅返回该数据帧的值,还返回一个可读的描述。Pandas缩短了此输出,因此在终端中打印时不会太长
因此,它不是语句中的中的错误。如果需要这样做,请使用问题中的第二段代码
作为参考,str(report[0:len(report)])
的输出如下:
col1 col2
0 0 AG100
1 1 AG100
2 2 AG100
3 3 AG100
4 4 AG100
5 5 AG100
6 6 AG100
7 7 AG100
8 8 AG100
9 9 AG100
10 10 AG100
11 11 AG100
12 12 AG100
13 13 AG100
14 14 AG100
15 15 AG100
16 16 AG100
17 17 AG100
18 18 AG100
19 19 AG100
20 20 AG100
21 21 AG100
22 22 AG100
23 23 AG100
24 24 AG100
25 25 AG100
26 26 AG100
27 27 AG100
28 28 AG100
29 29 AG100
.. ... ...
70 70 AG100
71 71 AG100
72 72 AG100
73 73 AG100
74 74 AG100
75 75 AG100
76 76 AG100
77 77 AG100
78 78 AG100
79 79 AG100
80 80 AG100
81 81 AG100
82 82 AG100
83 83 AG100
84 84 AG100
85 85 AG100
86 86 AG100
87 87 AG100
88 88 AG100
89 89 AG100
90 90 AG100
91 91 AG100
92 92 AG100
93 93 AG100
94 94 AG100
95 95 AG100
96 96 AG100
97 97 AG100
98 98 AG100
99 99 AG100
[100 rows x 2 columns]
您应该尝试使用更多pythonic方法在数据帧中循环,例如report.iterrows()中的行的,
,而不是跟踪计数器