簡體   English   中英

Pandas有條件的新列基於在其他數據框列中找到的期間

[英]Pandas Conditional new column based on period found in other dataframe column

我有一個帶有文件擴展名的數據框。 有些人在其中有句點,我試圖創建一個新的列,標記其中是否包含句點或無條件。 如果我只想獲取包含句點的行,則可以使用: send_rec_file_url[send_rec_file_url['file_name'].str.contains('\\.')]

如何創建如下所示的新列?

df
    file_name
0   png 
1   jpg
2   jpg
3   pdf
4   pdf
5   xlsx
6   docx.pdf
7   txt.scf
8   pdf
9   TXT.vbs
10  read_this.pdf 

所需的輸出:

df
    file_name      has_period
0   png            no
1   jpg            no
2   jpg            no
3   pdf            no
4   pdf            no
5   xlsx           no
6   docx.pdf       yes
7   txt.scf        yes
8   pdf            no
9   TXT.vbs        yes
10  read_this.pdf  yes

您需要使用掩碼來更改列的值。

df['has_period'] = 'no'
df.loc[df['file_name'].str.contains('\.'), 'has_period'] = 'yes'

輸出:

           file_name has_period
0             png         no
1             jpg         no
2             jpg         no
3             pdf         no
4             pdf         no
5            xlsx         no
6        docx.pdf        yes
7         txt.scf        yes
8             pdf         no
9         TXT.vbs        yes
10  read_this.pdf        yes

你可以試試:

df['has_period'] = ["Yes" if '.' in i else "No" for i in df['file_name']]

輸出:

        file_name has_period
0             png         No
1             jpg         No
2             jpg         No
3             pdf         No
4             pdf         No
5            xlsx         No
6        docx.pdf        Yes
7         txt.scf        Yes
8             pdf         No
9         TXT.vbs        Yes
10  read_this.pdf        Yes

注意:pandas .str訪問器非常慢,此解決方案應優於.str訪問器解決方案。

暫無
暫無

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

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