簡體   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