簡體   English   中英

從pandas dataframe中刪除包含字符串中數字值的行

[英]delete rows containing numeric values in strings from pandas dataframe

我有一個包含2列的pandas數據框,類型和文本text列包含字符串值。 如何刪除文本列中包含一些數值的行。 例如:

`ABC 1.3.2`, `ABC12`, `2.2.3`, `ABC 12 1`

我在下面試過,但得到一個錯誤。 知道為什么會出錯嗎?

df.drop(df[bool(re.match('^(?=.*[0-9]$)', df['text'].str))].index)

在你的情況下,我認為最好使用簡單的索引而不是丟棄。 例如:

>>> df
       text type
0       abc    b
1    abc123    a
2       cde    a
3  abc1.2.3    b
4     1.2.3    a
5       xyz    a
6    abc123    a
7      9999    a
8     5text    a
9      text    a


>>> df[~df.text.str.contains(r'[0-9]')]
   text type
0   abc    b
2   cde    a
5   xyz    a
9  text    a

找到沒有數字文本的任何行

解釋:

df.text.str.contains(r'[0-9]')

返回一個布爾系列,其中有任何數字:

0    False
1     True
2    False
3     True
4     True
5    False
6     True
7     True
8     True
9    False

並且您可以使用~來索引數據幀,只要返回false

來自jpp的數據

s[s.str.isalpha()]
Out[261]: 
0    ABC
2    DEF
6    GHI
dtype: object

假設您將numeric定義為x.isdigit()True ,您可以使用any生成器表達式並通過pd.Series.apply創建布爾掩碼:

s = pd.Series(['ABC', 'ABC 1.3.2', 'DEF', 'ABC12', '2.2.3', 'ABC 12 1', 'GHI'])

mask = s.apply(lambda x: not any(i.isdigit() for i in x))

print(s[mask])

0    ABC
2    DEF
6    GHI
dtype: object

正如我在評論中提到的那樣,你對數字的定義是什么? 如果我們使用split()跟蹤python的isnumeric ,我們得到以下內容:

import pandas as pd

將pandas導入為pd

df = pd.DataFrame({
    'col1': ['ABC', 'ABC 1.3.2', 'DEF', 'ABC12', '2.2.3', 'ABC 12 1', 'GHI']
})

m1 = df['col1'].apply(lambda x: not any(i.isnumeric() for i in x.split()))
m2 = df['col1'].str.isalpha()
m3 = df['col1'].apply(lambda x: not any(i.isdigit() for i in x))
m4 = ~df['col1'].str.contains(r'[0-9]')

print(df.assign(hasnonumeric=m1,isalhpa=m2, isdigit=m3, contains=m4))

# Opting for hasnonumeric
df = df[m1]

打印:

        col1  hasnonumeric  isalhpa  isdigit  contains
0        ABC          True     True     True      True
1  ABC 1.3.2          True    False    False     False
2        DEF          True     True     True      True
3      ABC12          True    False    False     False
4      2.2.3          True    False    False     False
5   ABC 12 1         False    False    False     False
6        GHI          True     True     True      True

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM