python-3.x - Python根据值的右子字符串从Dataframe中删除行
问题描述
我有一个 pandas DataFrame,我想从中删除值以 xx.x1 或 xx.x6 结尾的行。
格式错误请见谅,这是我的第一篇文章...
现有输出:
UID Col1 Col2 Col3
001 abcd 44.05 xyz
002 bcde 56.01 oig
003 cdef 88.00 itr
004 defg 33.76 lkj
005 efgh 22.00 hgf
期望的输出:
UID Col1 Col2 Col3
001 abcd 44.05 xyz
003 cdef 88.00 itr
005 efgh 22.00 hgf
我可以打印我认为可以与运算符一起使用的 Col2 的子字符串:
df = df.iloc[2].str[-2:]
产生以下输出:
Col2
5
1
0
6
0
我试过了
df = df[df.iloc[4].str[-1:] != 1 or 6]
但这会引发“ValueError:Series 的真值不明确。使用 a.empty、a.bool()、a.item()、a.any() 或 a.all()。”
请问有什么建议吗?
解决方案
IIUC 你可以使用isin
:
df.loc[~df["Col2"].astype(str).str[-1].isin(["1","6"])]
或与str.contains
:
df.loc[~df["Col2"].astype(str).str.contains("\d{2}.\d[16]")]
UID Col1 Col2 Col3
0 1 abcd 44.05 xyz
2 3 cdef 88.00 itr
4 5 efgh 22.00 hgf
推荐阅读
- python - 检查数组中的 n 个元素是否在增加
- javascript - 未捕获的 TypeError:无法设置 null 错误的属性“innerHTML”,但元素不为 null
- python - 限制我的 HTML 页面中的用户表单输入,直到我的 Python 函数完成运行,Flask
- sql - 将相关表中的值转换为逗号分隔的列表
- c - 用于数组初始化的 C 宏
- pandas - 如何从 Pandas 数据框中获取一组值?
- javascript - Javascript-如何在另一个函数内使用 push 方法将字符串推送到对象内的数组?
- react-native - TypeError: undefined is not an object (evalating '_this.state.data.name.filter') 反应原生
- git - Git 可以支持的最大最优 repo 大小是多少?
- excel-formula - 我有数据并设定了限制。我想确定有多少数据超出限制以及多少