首页 > 解决方案 > Python panda 过滤

问题描述

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

“语法错误:无效语法”

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

另外,请帮助我了解如何过滤多个项目 - 例如在上面的代码中,我想保留所有单元格名称为LM-MP-NW-URBAN-GROCERY S & SPAZA或的数据KZN-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') 

标签: pythonpandasfiltering

解决方案


Cell Name这是在 Pandas 中基于多个值过滤行的方式:

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]

推荐阅读