簡體   English   中英

如何根據列值的長度過濾 dataframe 行

[英]How to filter dataframe row based on length of column values

我有一個 dataframe 有一列包含以下字符串:

df=pd.DataFrame(['Hello world', 'World is good', 'Worldisnice hello'], columns=['A'])

df
                     A
0         'Hello world'
1       'World is good'
2   'Worldisnice hello'


我正在嘗試獲取包含一個長度為 11 個字符的單詞的行

我正在使用以下代碼,它給了我字符串的長度,而不是列內的單詞

df = df[df['A'].apply(lambda x: len(x) == 11)]

得到以下結果:

df
                     A
0         'Hello world'

output 應該是:

df
                     A
0   'Worldisnice hello'

因為是唯一一個包含一個長度等於 11 個字符的單詞

謝謝

您的代碼中的len(x)正在檢查整個字符串的 len 。

>>> df.A.str.len()
 0    11
 1    13
 2    17

您需要做的是將字符串拆分為單詞並檢查任何單詞的長度是否為 == 11。

下面的代碼是應該做的工作。

>>> df[df['A'].apply(lambda x: any(len(y) == 11 for y in x.split()))]
                  A
2  Worldisnice hello

另一種方法:

df[df.A.str.split().map(lambda x: any(len(y) == 11 for y in x))]

提供:

                   A
2  Worldisnice hello

我喜歡明確定義簡單的過濾函數。 我發現它更具可讀性和可維護性。

In [8]: def f(row):
   ...:     words = row.A.split()
   ...:     for w in words:
   ...:         if len(w) == 11:
   ...:             return True
   ...: 

In [9]: df.loc[df.apply(f, axis=1) == True]
Out[9]: 
                   A
2  Worldisnice hello

暫無
暫無

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

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