Pandas有条件的新列基于在其他数据框列中找到的期间

时间:2019-09-16 19:49:49

标签: python pandas

我有一个带有文件扩展名的数据框。有些人在其中有句点,我试图创建一个新的列,标记其中是否包含句点或无条件。如果我只想获取包含句点的行,请使用: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

2 个答案:

答案 0 :(得分:3)

您需要使用掩码来更改列的值。

https://login.microsoftonline.com/<Tenant Id>/oauth2/v2.0/token

输出:

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

答案 1 :(得分:2)

您可以尝试:

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访问器解决方案。