将xlsx文件中的特定行添加到使用pandas列表

我想添加一些xlsx文件到打开的列表,但不知道如何去做。 我有几个像这样的数据的xlsx文件:

ABCDEFGH 1 A10 2 A10 2 AB 2 A105 1 A105 2 AB .... 10 A250 4 A250 4 AB 

我想要列E的单元格值的总和减去列B的单元格值的行不等于零以添加到列表。 所以在上面的例子中,我只希望将第二行添加到列表中,因为2 – 1是1而不是0。 所以之后列表应该包含这个:

  A105 1 A105 2 AB 

我不知道如何做到这一点,并尝试了一些与pandas和openpyxl,但我还没有得到它的权利呢。 任何人都可以帮我一路?

这是代码的开始:

 import pandas as pd import glob numbers = [] rapp = r"C:\Myfolder files = glob.glob(rapp) for file in files: df = pd.read_excel(excelfile) if df.iloc[:,4] - df.iloc[:,1] != 0: #I get an errormessage on this, and do not know how to express this properly. numbers = #I do not know what to write here either, as I somehow need it to be row.tolist() Traceback: if df.iloc[:,4] - df.iloc[:,1] != 0: ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all(). 

感谢您的帮助!

pandas与数组一起工作是有问题的,而不是标量。

比较输出是:

 print ((df.iloc[:, 4] - df.iloc[:, 1]) != 0) 0 False 1 True 2 False dtype: bool 

有2个False和1个True

if由于python confused ,就不能使用了 – 有TrueFalse – 输出是什么?

您可以首先比较列EB ,通过boolean indexing进行过滤,select列为loc ,输出列表:

 m = df['E'].ne(df['B']) print (m) 0 False 1 True 2 False dtype: bool 

解决scheme与iloc

 m = df.iloc[:, 4].ne(df.iloc[:, 1]) pos = [0,1,3,7] print (df.loc[m, df.columns[pos]].values.tolist()) [['A105', 1, 'A105', 'AB']] 

编辑你的解决scheme:

 m = (df.iloc[:, 4] - df.iloc[:, 1]) != 0 pos = [0,1,3,7] print (df.loc[m, df.columns[pos]].values.tolist()) [['A105', 1, 'A105', 'AB']] 

多列解决scheme:

 print (df) ABCDEFGH 0 A10 2 NaN A10 2 NaN NaN AB 1 A10 3 NaN A10 2 NaN NaN AB 2 A105 1 NaN A105 2 NaN NaN AB 3 A250 4 NaN A250 4 NaN NaN AB m = (df.iloc[:, 4] - df.iloc[:, 1]) != 0 print (m) 0 False 1 True 2 True 3 False dtype: bool pos = [0,1,3,7] print (df.loc[m, df.columns[pos]].values.tolist()) [['A10', 3, 'A10', 'AB'], ['A105', 1, 'A105', 'AB']]