简体   繁体   English

python:dataframe 列迭代在第一轮后停止

[英]python: dataframe column iteration stops after first round

I am trying to print the index where 1 is contained in a specific column of a dataframe.我正在尝试打印 dataframe 的特定列中包含 1 的索引。 The for loop meets the condition at the first iteration and goes back to it instead of moving forward. for 循环在第一次迭代时满足条件并返回它而不是向前移动。 I have looked all over and have found others with the same problem, however, I still cannot figure out the solution.我环顾四周,发现其他人有同样的问题,但是,我仍然无法找出解决方案。

import pandas as pd
d = {'a': [0.1, 0.2,0.3,0.4,0.5,0.6], 'b': [0.6, 0.8,0.3,0.4,0.1,0.1],
     'c': [0.7, 0.3,0.9,0.4,1.0,0.2],'d': [1,0,0,1,0,1]}
df = pd.DataFrame(data=d)
klist=[]
for i in (df.d):
    if  i == 1:
        klist.append(df.d.tolist().index(i))
           
print(klist) # should print [0, 3, 5] instead of [0, 0, 0]

Use indexing rather than a loop使用索引而不是循环

klist = df[df['d'] == 1].index.tolist()
print(klist)

# Output:
[0, 3, 5]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM