pandas dataframe 过滤——apply最灵活!!!
按照某特定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
或者是:
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过滤!
pandas dataframe 过滤——apply最灵活!!!的更多相关文章
- pandas DataFrame apply()函数(1)
之前已经写过pandas DataFrame applymap()函数 还有pandas数组(pandas Series)-(5)apply方法自定义函数 pandas DataFrame 的 app ...
- pandas DataFrame apply()函数(2)
上一篇pandas DataFrame apply()函数(1)说了如何通过apply函数对DataFrame进行转换,得到一个新的DataFrame. 这篇介绍DataFrame apply()函数 ...
- Pandas DataFrame数据的增、删、改、查
Pandas DataFrame数据的增.删.改.查 https://blog.csdn.net/zhangchuang601/article/details/79583551 #删除列 df_2 = ...
- Pandas DataFrame 函数应用和映射
apply Numpy 的ufuncs通用函数(元素级数组方法)也可用于操作pandas对象: 另一个常见的操作是,将函数应用到由各列或行所形成的一维数组上.Dataframe的apply方法即可实现 ...
- 【338】Pandas.DataFrame
Ref: Pandas Tutorial: DataFrames in Python Ref: pandas.DataFrame Ref: Pandas:DataFrame对象的基础操作 Ref: C ...
- 更改 pandas dataframe 中两列的位置
更改 pandas dataframe 中两列的位置: 把其中的某列移到第一列的位置. 原来的 df 是: df = pd.read_csv('I:/Papers/consumer/codeandpa ...
- pandas DataFrame的查询方法(loc,iloc,at,iat,ix的用法和区别)
pandas DataFrame的增删查改总结系列文章: pandas DaFrame的创建方法 pandas DataFrame的查询方法 pandas DataFrame行或列的删除方法 pand ...
- pandas.DataFrame对象解析
pandas.DataFrame对象类型解析 df = pd.DataFrame([[1,"2",3,4],[5,"6",7,8]],columns=[&quo ...
- pandas.DataFrame学习系列1——定义及属性
定义: DataFrame是二维的.大小可变的.成分混合的.具有标签化坐标轴(行和列)的表数据结构.基于行和列标签进行计算.可以被看作是为序列对象(Series)提供的类似字典的一个容器,是panda ...
随机推荐
- ZTree 获取选中的项
var zTreeOjb = $.fn.zTree.getZTreeObj("zTreeId"); //ztree的Id zTreeId 获取复选框/单选框选中的节点:var ch ...
- [从零开始搭网站四]CentOS配置Tomcat
点击下面连接查看从零开始搭网站全系列 从零开始搭网站 上一章带大家配置了JDK,那么现在就要来配置Tomcat容器了. 1:去 http://tomcat.apache.org/download-90 ...
- codeforces 768D Jon and Orbs
题目链接:http://codeforces.com/problemset/problem/768/D 令$f[i][j]$表示当前产生过了$i$个球,产生过了$j$个不同的球的概率. ${Ans_i ...
- Systemd初始化进程/RHEL 6系统中System V init命令与RHEL 7系统中systemctl命令的对比
Linux操作系统的开机过程是这样的,即从BIOS开始,然后进入Boot Loader,再加载系统内核,然后内核进行初始化,最后启动初始化进程.初始化进程作为Linux系统的第一个进程,它需要完成Li ...
- composer require 指定版本
默认 composer require endroid/qr-code 指定版本 composer require endroid/qr-code 1.9.3 # composer require e ...
- fit_transform和transform的区别
来自:泡泡糖nana 来自:俞驰 1. fit_transform是fit和transform的组合. 2. fit(x,y)传两个参数的是有监督学习的算法,fit(x)传一个参数的是无监督学习的算法 ...
- django分页 Paginator
分页功能是几乎所有的网站上都需要提供的功能,当你要展示的条目比较多时,必须进行分页,不但能减小数据库读取数据压力,也有利于用户浏览. Django又很贴心的为我们提供了一个Paginator分页工具, ...
- 异常处理.VC++
ZC:个人这样 理解 C++的异常处理: ZC: (1).C++标准异常处理,try{}catch{} 抛异常:throw() [ 据说是包装的Windows函数RaiseException() ] ...
- VS2010:“error C2712: 无法在要求对象展开的函数中使用 __try”
ZC:这个错误是在使用 "__try{...} __except(EXCEPTION_EXECUTE_HANDLER){}"时 遇到的 http://blog.csdn.net/c ...
- 关于repaint和reflow的笔记
repaint(重绘) ,repaint发生更改时,元素的外观被改变,且在没有改变布局的情况下发生,如改变outline,visibility,background color,box-shadow不 ...