如何从许多已创建的行中访问一行

How to access one row out of many founded

我在使用 openpyxl 时遇到问题,但用户 Eric and H. Trizi 解决了它。不幸的是还有另一个问题。他们为我提供了如何 select 包含特定产品名称(在本例中为 ABC)的行的解决方案,但我不知道如何单独访问搜索结果。

这是 Eric 的代码:

from openpyxl import load_workbook
wb = load_workbook("report.xlsx")
ws = wb.active

for row in ws.rows:
   if row[4].value == "ABC":
       for cell in row:
           print(cell.value, end=" ")
       print()

这是 H. Trizi 的:

    import pandas as pd

    df = pd.read_excel("path_to_excel_file")
    df_abc = df[df["Products"] == "ABC"] # this will only contain 2,4,6 rows

当涉及到 selecting 包含“ABC”产品的所有行时,它们都非常有效,但是有没有办法访问包含 ABC 产品名称的每一行(然后是其中的每个单元格)分开?

我想要实现的是分别访问产品名称为 ABC 的每一行,然后将其单元格保存到变量中。

所以一步一步: 1.Find 包含 ABC 乘积的所有行都在行中(在本例中为 2、4、6)- 由 Eric 和 H. Trizi 解决 2.Get 第 2 行并将其分解为将分配给变量(名称、姓氏、订单号等)的单元格 3.对第4行做同样的事情 4.对第6行做同样的事情 5.etc。 PS。 excel 报告

中提供了数据

你可以用的很慢iterrows:

for i, row in df_abc.iterrows():
    print (i)
    name = row['name']
    surname = row['surname']

或者快一点itertuples

for i in df_abc.itertuples():
    name = i.name
    surname = i.surname

另一种解决方案是通过to_dict将过滤后的DataFrame转换为字典列表,它应该是最快的:

L = df_abc.to_dict(orient='r')

for x in L:
    print (x)
    name = x['name']
    surname = x['surname']

样本:

df = pd.DataFrame({'surname':list('abcdef'),
                   'Products':['ABC','ABC','d','d','ABC','f'],
                   'val':[7,8,9,4,2,3],
                   'name':list('DFERTH')})

print (df)
  surname Products  val name
0       a      ABC    7    D
1       b      ABC    8    F
2       c        d    9    E
3       d        d    4    R
4       e      ABC    2    T
5       f        f    3    H

df_abc = df[df["Products"] == "ABC"]
print (df_abc)
  surname Products  val name
0       a      ABC    7    D
1       b      ABC    8    F
4       e      ABC    2    T

L = df_abc.to_dict(orient='r')
print (L)
[{'surname': 'a', 'Products': 'ABC', 'val': 7, 'name': 'D'},
 {'surname': 'b', 'Products': 'ABC', 'val': 8, 'name': 'F'},
 {'surname': 'e', 'Products': 'ABC', 'val': 2, 'name': 'T'}]

for x in L:
    print (x)
    print (x['name'])
    print (x['surname'])

D
a
{'surname': 'b', 'Products': 'ABC', 'val': 8, 'name': 'F'}
F
b
{'surname': 'e', 'Products': 'ABC', 'val': 2, 'name': 'T'}
T
e    

编辑:

对于 select 每个值单独 variable - 没有必要,因为可以使用 list of dictionary,select 每个 dictionary 通过索引和然后 select dict 的每个值:

#selected first dictionary of list by indexing ([0]) and then dictionary by key (name)
print (L[0]['name'])
D
print (L[0]['surname'])
a

print (L[1]['name'])
F
print (L[1]['surname'])
b

print (L[2]['name'])
T
print (L[2]['surname'])
e