如何用python代码实现筛选

Python016

如何用python代码实现筛选,第1张

用python代码实现筛选的方法:

python中的if语句可以实现筛选的效果。例如:筛选出列表里的数字就可以用“if type(i) == int”语句来筛选

示例代码如下:

执行结果如下:

更多Python知识,请关注:Python自学网!!

file1_path ='E:/Users/lenovo/Desktop/中视/622召回.csv' # 源数据

格式:file1=pd.read_csv(file1_path)

pd.read_csv(file1_path,encoding='gbk')

pd.read_csv(file1_path,encoding='gbk',skiprows=[2,3])

pd.read_csv(file1_path,encoding='gbk',skiprows=lambda x:x%2==1)

pd.read_csv(file1_path,encoding='gbk',keep_default_na=False)

new=pd.DataFrame()

new.new[[0,1,2]]

new.new[0:2]

查询结果同上

new.loc[new['激活数']>1000]

loc和iloc的区别:

     loc:纯标签筛选

     iloc:纯数字筛选

#筛选出new的某两列

new=new.loc[:,['phone','收件人姓名']]

#筛选new的第0,1列

new.iloc[:,[0,1]]

使用‘==’筛选-筛查“崔旭”的人(只能筛查指定明确的)

#new=file1.loc[(file1['收件人姓名']=='崔旭')|(file1['收件人姓名']=='崔霞')]

#print(new)

#使用loc函数筛选-str.contains函数-筛查名字中包含'亮'和'海'的人

#new=file1.loc[file1['收件人姓名'].str.contains('亮|海')]

#print(new)

#使用loc函数筛选-str.contains函数-筛查'崔'姓的人

#new=file1.loc[file1['收件人姓名'].str.startswitch('崔')]

#print(new)

df = df[(df['DEPOSIT_PAY_TIME_x'] .notnull() ) &(df['DEPOSIT_PAY_TIME_x'] != "" )]

print("during_time(number)=0的个数:",newdata[newdata['during_time(number)'] ==0].count()['during_time(number)'])

print("during_time(number)=1,2,3的个数:",newdata[(newdata['during_time(number)'] >0) &(newdata['during_time(number)'] <4)].count()['during_time(number)'])

print(newdata[newdata['during_time(number)'] ==0])

newdata[newdata['Team']. isin (['England','Italy','Russia'])][['Team','Shooting Accuracy']]

df.年龄.value_counts()

1.修改指定位置数据的值(修改第0行,’创建订单数‘列的值为3836)

new.loc[0,'创建订单数']=3836

2.替换‘小明’-‘xiaoming’

df.replace({'name':{'小明':'xiaoming'}})

3.批量替换某一列的值(把‘性别’列里的男-male,女-felmale)

方法一:df['性别']=df['性别'].map({'男':'male','女':'female'})

方法二:df['性别'].replace('female','女',inplace=True)

               或df['性别']=df['性别'].replace('female','女')                这就是inplace的作用

                +df['性别'].replace('male','男',inplace=True)

4.替换列索引

df.columns=['sex','name','height','age']

或者:df.rename(columns={'性别':'sex','姓名':'name','身高':'height','年龄':'age'})

5.删除某一列

del df['player']

6. 删除某一列(方法二),删除某一行(默认axis=0删除行,为1则删除列)

删除某一列(方法二)

df.drop('性别',axis=1)

删除某一行

df.drop(1,axis=0)

file1=pd.read_csv(file1_path)

file2=pd.read_csv(file2_path)

new1=pd.DataFrame()

new1['phone']=file1['phone']

new1['contact_time']=file1['contact_time']

new2=pd.DataFrame()

new2['phone']=file2['phone']

new2['submission_audit_time']=file2['提交审核时间']

newdata=pd.merge(new1,new2,on='phone',how='left')

df=pd.concat([df1,df2],axis=0)

4.2.2 横向表连接

df=pd.concat([df1,df2],axis=1)

df1['地区'].str.split('·',3,expand=True)

df1:

df1[['城市', '城区','地址']] = df1['地区'].str.split('·', 3, expand = True)

5.1 缺失值删除

data.dropna(axis=0,subset = ["Age", "Sex"])   # 丢弃‘Age’和‘Sex’这两列中有缺失值的行

data.dropna(how = 'all')    # 传入这个参数后将只丢弃全为缺失值的那些行

data.dropna(axis = 1)       # 丢弃有缺失值的列(一般不会这么做,这样会删掉一个特征)

data.dropna(axis=1,how="all")   # 丢弃全为缺失值的那些列

5.2 缺失值填充:pandas.DataFrame.fillna()函数

DataFrame.fillna(value=None, method=None, axis=None, inplace=False, limit=None, downcast=None, **kwargs)

功能:使用指定方法填充NA/NaN值

其中inplace=True就是直接在原有基础上填满

5.3 缺失值查询:

缺失值数量查询:df.isnull().sum()

缺失值行查询:df[df.isnull().T.any()]

newdata['during_time']=pd.to_datetime(newdata['submission_audit_time'])-pd.to_datetime(newdata['contact_time'])

newdata['during_time(number)']=(pd.to_datetime(newdata['submission_audit_time'])-pd.to_datetime(newdata['contact_time'])).apply(lambda x: x.days)

new=pd.DataFrame()

new=newdata[newdata['during_time(number)'] ==0]

new.to_csv(save_path,encoding='utf-8-sig')

将数据按行拆分并存储到不同的csv文件中:

path='C:/Users/EDZ/Desktop/工作/2021.08.19/'

for i in range(0,30):

    df.loc[[i]].to_csv(path+str(i)+'.csv',encoding='gbk')

df = df[['购药日期', '星期','社保卡号','商品编码', '商品名称', '销售数量', '应收金额', '实收金额' ]]

txtfile=open(r'test.txt',"r")

newtxtfile=open(r'new.txt',"w")

linelist=[]

for line in txtfile:

    linelist.append(line)

    if len(linelist)==4:

        if not linelist[1].startswith(r'aaa'):

            newtxtfile.writelines(linelist)

        linelist=[]

if len(linelist)>1:

    if not linelist[1].startswith(r'aaa'):

            newtxtfile.writelines(linelist)

elif len(linelist)==1:

    newtxtfile.writelines(linelist)

txtfile.close()

newtxtfile.close()

读取文件test.txt,将每四行中第二行以aaa开始的去除,写入新文件new.txt中