Python熊猫过滤

时间:2018-11-01 10:31:34

标签: python pandas filtering

我正在尝试过滤文件,以便保留“单元名称”为LM-MP-NW-URBAN-GROCERY S & SPAZA的数据行,但是当我运行上述代码时,我得到了

  

“ SyntaxError:语法无效”

我使用带有数字的列尝试了该代码,并使用了==<, >符号。

另外,请帮助我了解如何过滤多个项目-例如,在上面的代码中,我想保留单元格名称为LM-MP-NW-URBAN-GROCERY S & SPAZAKZN-GP-EC-URBAN_GROCERY S & SPAZA的所有数据

提前谢谢

#Import libraries 
import pandas as pd
import os
import glob
#Set working directory and create list of raw files 
os.chdir(r'C:\Users\Shab7002\Documents\data science\18 10 9\nestle 708294\infant')
lorf = glob.glob('*.txt')
#Create empty dataframe and concatenate raw files 
df_mrgd = pd.DataFrame()

for file in lorf:
    df_add = pd.read_csv(file,sep='\t', encoding='latin-1')
    df_mrgd = pd.concat([df_mrgd, df_add.head(10)])
    #Filter columns
filt_col = ['PeriodVFP', 'Product name', 'MBD Name', 'Outlet name', 'Cell Name', 'Sales', 'SalesValue', 'SalesVolume']
#filter rows
df_filtered = df_mrgd[filt_col].query('Cell Name== "LM-MP-NW-URBAN-GROCERY S & SPAZA"')
 #and export concatenated data frame 
df_filtered.to_excel('mu.xlsx') 

1 个答案:

答案 0 :(得分:1)

这是基于熊猫中多个Cell Name值来过滤行的方式:

df_filtered = df_mrgd.loc[df_mrgd['Cell Name'].isin(["LM-MP-NW-URBAN-GROCERY S & SPAZA", "KZN-GP-EC-URBAN_GROCERY S & SPAZA"]), filt_col]