python - 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')
解决方案
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]
推荐阅读
- state-machine - 如何使用存储引擎持久化 Saga 实例并避免竞争条件
- gradle - build.gradle.kts & multi-module-project:如何添加其他项目以便传递依赖也可用
- c# - 如何在 c# 中将 OpenCV 2.4 源代码转换为 3.0
- swift - 为什么我必须解开脆弱的自我?
- multithreading - "threadgroup_barrier" makes no difference
- python - 如何使用 Selenium 和 Python 单击文本作为联系人的元素
- javascript - Canvas Js在每个栏上写不同的值C# Mvc
- sql - 如何获取每个 user_id 的最后一个值(postgreSQL)
- netlogo - 在 Netlogo 中为路线着色
- java - 如何将标签添加到 StepAreaChart