0

**我是新的 python DF,我有一个两列的 excel 文件,我想在其中循环遍历它的行。如果列“数量”超过其行的值为零,我想从第一列获取每一行的横档值并保留在列表中。

import pandas as pd**

    df = pd.read_excel(file)
    reuslt =[]
    for i in range(len(df)):
        amount = df.iloc[i,1]
        result.append(shelf)
    
    Example detial  excel file
    shelf  amount
    11        0
    13        1
    15        8
    18        0
    20        6
    22        0
    25        1`
4

1 回答 1

0

您不需要显式地迭代 - Pandas 为您提供了轻松搜索或过滤行所需的所有工具。

import pandas as pd

df = pd.DataFrame(
    {
        'shelf': [11,13,15,18,20,22,25],
        'amount': [0,1,8,0,6,0,1]
    }
)

# get DataFrame onyl with "zero amount shelfs"
df_zero_shelfs = df[df['amount']==0]
df_zero_shelfs

##################
Output:

  shelf amount
0   11  0
3   18  0
5   22  0

##################

# cast zero amount shelfs IDs to list
list_zero_shelfs = list(df_zero_shelfs['shelf'].values)
list_zero_shelfs
##################
Output:

[11, 18, 22]

[编辑]
如果你真的想坚持 for 循环(不建议):

result = []
for row in df.values:
    if row[1] == 0:
        result.append(row[0])
于 2021-04-13T10:54:16.870 回答