pandas dataframe 过滤——apply最灵活!!!

枫铃4年前 (2021-07-09)Python274

按照某特定string字段长度过滤:

import pandas as pd
 
df = pd.read_csv('filex.csv')
df['A'] = df['A'].astype('str')
df['B'] = df['B'].astype('str')
mask = (df['A'].str.len() == 10) & (df['B'].str.len() == 10)
df = df.loc[mask]
print(df)

Applied to filex.csv:

A,B
123,abc
1234,abcd
1234567890,abcdefghij
the code above prints

            A           B
2  1234567890  abcdefghij

或者是:

'''
遇到问题没人解答?小编创建了一个Python学习交流QQ群:857662006 寻找有志同道合的小伙伴,
互帮互助,群里还有不错的视频学习教程和PDF电子书!
'''
data={"names":["Alice","Zac","Anna","O"],"cars":["Civic","BMW","Mitsubishi","Benz"],
     "age":["1","4","2","0"]}
 
df=pd.DataFrame(data)
"""
df:
  age        cars  names
0   1       Civic  Alice
1   4         BMW    Zac
2   2  Mitsubishi   Anna
3   0        Benz      O
Then:
"""
 
df[
df['names'].apply(lambda x: len(x)>1) &
df['cars'].apply(lambda x: "i" in x) &
df['age'].apply(lambda x: int(x)<2)
  ]
"""
We will have :
  age   cars  names
0   1  Civic  Alice
"""

最灵活的是用apply:

def load_metadata(dir_name):   
    columns_index_list = [
        MetaIndex.M_METADATA_ID_INDEX,
        MetaIndex.M_SRC_IP_INDEX,
        MetaIndex.M_DST_IP_INDEX,
        MetaIndex.M_SRC_PORT_INDEX,
        MetaIndex.M_DST_PORT_INDEX,
        MetaIndex.M_PROTOCOL_INDEX,
        MetaIndex.M_HEADER_H,
        MetaIndex.M_PAYLOAD_H,
        MetaIndex.M_TCP_FLAG_H,
        MetaIndex.M_FLOW_FIRST_PKT_TIME,
        MetaIndex.M_FLOW_LAST_PKT_TIME,
        MetaIndex.M_OCTET_DELTA_COUNT_FROM_TOTAL_LEN,
    ]
    columns_name_list = [
        "M_METADATA_ID_INDEX",
        "M_SRC_IP_INDEX",
        "M_DST_IP_INDEX",
        "M_SRC_PORT_INDEX",
        "M_DST_PORT_INDEX",
        "M_PROTOCOL_INDEX",
        "M_HEADER_H",
        "M_PAYLOAD_H",
        "M_TCP_FLAG_H",
        "M_FLOW_FIRST_PKT_TIME",
        "M_FLOW_LAST_PKT_TIME",
        "M_OCTET_DELTA_COUNT_FROM_TOTAL_LEN",
    ]
 
    def metadata_parse_filter(row):
        try:
            if row['M_PROTOCOL_INDEX'] != 6:
                return False
            if len(row['M_HEADER_H']) < 2 or len(row['M_PAYLOAD_H']) < 2 or not is_l34_tcp_metadata(row['M_METADATA_ID_INDEX']):
                return False
            first_time = row['M_FLOW_FIRST_PKT_TIME'].split('-')
            last_time = row['M_FLOW_LAST_PKT_TIME'].split('-')
 
            flow_first_pkt_time = int(first_time[0])
            rev_flow_first_pkt_time = int(first_time[1])
 
            flow_last_pkt_time = int(last_time[0])
            rev_flow_last_pkt_time = int(last_time[1])
            if flow_first_pkt_time > flow_last_pkt_time or rev_flow_first_pkt_time > rev_flow_last_pkt_time:
                return False
            return True
        except Exception as e:
            return False
 
    for root, dirs, files in os.walk(dir_name):
        for filename in files:
            file_path = os.path.join(root, filename)
            df = pd.read_csv(file_path, delimiter='^', usecols=columns_index_list, names=columns_name_list, encoding='utf-8', error_bad_lines=False, warn_bad_lines=True, header=0, lineterminator="\n")
            filter_df = df.loc[df.apply(metadata_parse_filter, axis=1)]
            yield filter_df

直接按照row过滤!

相关文章

利用python同步windows和linux文件

写python脚本的初衷,每次在windows编辑完文件后,想同步到linux上去,只能够登录服务器,...

爬虫基本原理

爬虫基本原理 一、爬虫是什么? 百度百科和维基百科对网络爬虫的定义:简单来说爬虫就是抓取目标网站内容的工具,一般是根据定义的行...

Django 函数和方法的区别

函数和方法的区别 1、函数要手动传self,方法不用传 2、如果是一个函数,用类名去调用,如果是一个方法...

Django 知识补漏单例模式

单例模式:(说白了就是)创建一个类的实例。在 Python 中,我们可以用多种方法来实现单例模式&#x...

Django基础知识MTV

Django简介 Django是使用Python编写的一个开源Web框架。可以用它来快速搭建一个高性能的网站。 Django也是一个MVC框架。但是在Dj...

Python mysql 索引原理与慢查询优化

一 介绍 为何要有索引? 一般的应用系统,读写比例在10:1左右,而且插入操作和一般的更新操作很少出现性能问题,...

发表评论

访客

看不清,换一张

◎欢迎参与讨论,请在这里发表您的看法和观点。