首页 > 解决方案 > 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()。”

请问有什么建议吗?

标签: python-3.xpandasdataframe

解决方案


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

推荐阅读