簡體   English   中英

根據 Pandas 數據框中列中的值過濾數據

[英]Filtering the data based on values in the columns in pandas dataframe

我最近一直在研究一些數據。 在過濾過程中,我發現一些列有一些問題。 我只想在 Branch 列的最后保留那些帶有 ')' 的行。

我嘗試了幾種選擇,但我想找到最快的方法來解決它。

這是我一直在研究的數據的一部分。

由於您沒有以文本形式提供數據,我創建了一個示例數據框:

輸入:

d = {'college_name': ['College {}'.format(i+1) for i in range(8)], 'branch': ['Civil Enigineering '+ '(4 Years)'*(i%2) for i in range(8)]}
df = pd.DataFrame(data=d, columns=['college_name','branch'])
df

輸出:

    college_name    branch
0   College 1   Civil Enigineering
1   College 2   Civil Enigineering (4 Years)
2   College 3   Civil Enigineering
3   College 4   Civil Enigineering (4 Years)
4   College 5   Civil Enigineering
5   College 6   Civil Enigineering (4 Years)
6   College 7   Civil Enigineering
7   College 8   Civil Enigineering (4 Years)

Pandas 系列內置了字符串處理方法。 您可以使用 str.endswith(')') 來過濾您的數據。 請注意df['branch'].str.endswith(')')將返回一個布爾掩碼。

輸入:

df[df['branch'].str.endswith(')')]

輸出:

    college_name    branch
1   College 2   Civil Enigineering (4 Years)
3   College 4   Civil Enigineering (4 Years)
5   College 6   Civil Enigineering (4 Years)
7   College 8   Civil Enigineering (4 Years)

暫無
暫無

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

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