【问题标题】:python: dataframe column iteration stops after first roundpython:数据框列迭代在第一轮后停止
【发布时间】:2022-01-02 08:33:32
【问题描述】:

我正在尝试打印数据帧的特定列中包含 1 的索引。 for 循环在第一次迭代时满足条件并返回它而不是向前移动。 我找遍了,发现其他人也有同样的问题,但我还是想不出解决办法。

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]

【问题讨论】:

    标签: python pandas dataframe for-loop


    【解决方案1】:

    使用索引而不是循环

    klist = df[df['d'] == 1].index.tolist()
    print(klist)
    
    # Output:
    [0, 3, 5]
    

    【讨论】:

    • @johnjohns。它解决了你的问题吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-07
    • 1970-01-01
    • 2020-12-15
    • 1970-01-01
    • 2015-10-20
    • 1970-01-01
    相关资源
    最近更新 更多