簡體   English   中英

如何刪除包含超過 3 個非 ascii 字符的行

[英]How to remove rows containing more than 3 non-ascii character

我想刪除sms列具有超過 3 個垃圾值的所有記錄/行,只需將我想刪除下面給出的熊貓數據框中的第 4 行和第 5 行。

id    city    department    sms                    category
01    khi      revenue      quk respns.                1
02    lhr      revenue      good.                      1
03    lhr      revenue      greatœ1øið                 0
04    isb      accounts     ?xœ1øiûüð÷üœç8i            0
05    isb      accounts     %â¡ã‘ã¸$ãªã±t%rã«ãÿã©â£    0

預期數據幀:

id city department        sms   category
1  khi    revenue  quk respns.         1
2  lhr    revenue        good.         1
3  lhr    revenue   greatœ1øið         0

我們可以使用Series.str.count來計算sms列中每個字符串[^\\x00-\\x7F]則表達式模式[^\\x00-\\x7F]匹配單個非 ASCII 字符)的出現次數,然后使用Series.gt創建boolean mask並使用此掩碼用於過濾行:

m = df['sms'].str.count(r'[^\x00-\x7F]').gt(3)
df = df[~m]

結果:

   id city department          sms  category
0   1  khi    revenue  quk respns.         1
1   2  lhr    revenue        good.         1
2   3  lhr    revenue   greatœ1øið         0
ascii_string = set("""!"#$%&\'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~""")
for r, j in df.iterrows(): 
  for k , data in j.iteritems():
    total_count = len(data)
    ascii_count = sum(c in ascii_string for c in data)
    non_ascii_count = total_count - ascii_count
    if non_ascii_count > 3:
      #remove row
      df = df.drop([r])
      break

ascii-table 只拉伸到 127,這意味着如果我們執行ord(<character>)並且我們得到一個超過 127 的值,那么這不是一個有效的 Ascii-character。

使用這個,我們可以計算不是 Ascii 的字符數,並且只返回True的有 3 個或更少。

df.drop(df.loc[df["sms"].apply(lambda x: False if len([i for i in x if ord(i) > 127]) <= 3 else True)].index)

輸出:

   id city department          sms  category
0   1  khi    revenue  quk respns.         1
1   2  lhr    revenue        good.         1
2   3  lhr    revenue   greatœ1øið         0

暫無
暫無

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

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