繁体   English   中英

在 Python 中跨多个列应用 str.contains 的问题

[英]Issue in applying str.contains across multiple columns in Python

Dataframe:

col1          col2             col3
132jh.2ad3    34.2             65
298.487       9879.87          1kjh8kjn0
98.47         79.8             90
8763.3        7hkj7kjb.k23l    67
69.3          3765.9           3510

所需的 output:

col1          col2             col3
98.47         79.8             90
69.3          3765.9           3510

我尝试过的:(这不会删除所有带有字母数字值的行)

df=df[~df['col1'].astype(str).str.contains(r'[A-Ba-b]')] #for col1
df=df[~df['col2'].astype(str).str.contains(r'[A-Ba-b]')] #for col2
df=df[~df['col3'].astype(str).str.contains(r'[A-Ba-b]')] #for col3

我想删除所有字母数字行,并且只有包含数字的行。 Col1 和 Col2 有小数点,但 Col3 只有整数。
我已经尝试了一些其他类似的线程,但它没有用。

谢谢您的帮助!!

您可以只使用to_numeric

df[df.apply(pd.to_numeric, errors='coerce').notnull().all(1)]

Output:

    col1    col2  col3
2  98.47    79.8    90
4   69.3  3765.9  3510

跑:

df[~df.apply(lambda row: row.str.contains(r'[A-Z]', flags=re.I).any(), axis=1)]

(需要重新导入)。

您的正则表达式包含[AB] ,但它应该匹配所有字母(从AZ )。

编辑

如果您还有其他列,但您想将您的标准限制为仅指定的 3 个列,假设它们是连续的列,请运行:

df[~df.loc[:, 'col1':'col3'].apply(lambda row:
    row.str.contains(r'[A-Z]', flags=re.I).any(), axis=1)]

这样,您将与上面相同的 function 应用于这 3 列。

这是一个不需要使用apply (可能很慢)而是stack的解决方案

# stack and use isnumeric to see if str is a number or float
# then unstack and dropna
df[df.stack().str.replace('.','').str.isnumeric().unstack()].dropna()

    col1    col2  col3
2  98.47    79.8    90
4   69.3  3765.9  3510

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM