【问题标题】:How to create new column based on first column taking into account size of letter and list in Python Pandas? [duplicate]考虑到 Python Pandas 中字母和列表的大小,如何根据第一列创建新列? [复制]
【发布时间】:2021-09-09 12:10:29
【问题描述】:

我在 Python Pandas 中有 DataFrame,如下所示:

col1
--------
John Simon prd
agc Ann White
BeN and Ann

bad_list = ["Ben", "Wayne"]

我需要采取类似的方法:创建新列“col2”,如果“col1”中的值具有来自 bad_list 的值,则在“col2”中为该行提供“1”,否则为 0。

请注意,bad_list 和“col1”中的字母大小应被忽略,例如“col1”中的值为“BeN”,而 bad_list 中的值为“Ben”,因此它也应具有值“ 1" in "col2"

因此,根据上述数据框和条件,我需要如下结果:

col1            | col2
----------------|------
John Simon prd  |0
arc Ann White   |0
BeN and Ann     |1

“col2”中的最后一行的值为“1”,因为“Ben”在 bad_list 上,不要介意“col1”中的写为 BeN。 如何在 Python Pandas 中做到这一点?

【问题讨论】:

  • 将下面的解决方案稍微更改为:import re df['col2'] = df['col1'].str.contains('|'.join(bad_list), flags=re.IGNORECASE).astype(int) 主要更改是添加flags=re.IGNORECASE 以指示Pandas 忽略大小写。

标签: python pandas dataframe


【解决方案1】:

您可以通过str.title(),str.contains()astype()方法尝试:

df['col2']=df['col1'].str.title().str.contains('|'.join(bad_list)).astype(int)

df的输出:

    col1            col2
0   John Simon prd  0
1   agc Ann White   0
2   BeN and Ann     1  

逐步分解代码:

由于您的列表,即 bad_list 包含格式中的单词(第一个单词是大写的,其余的都是小单词)所以我们使用 Series.str.title() 像这样转换整个 Series('col1') 所以现在 Series('col1') 看起来像:

0    John Simon Prd
1     Agc Ann White
2       Ben And Ann
Name: col1, dtype: object

然后我们使用str.contains(),在检查bad_list 中的任何元素是否存在于Series('col1') 的行中后,它会为我们提供一个布尔系列:

0    False
1    False
2     True
Name: col1, dtype: bool

注意:

这里是contains()方法里面的代码:

'|'.join(bad_list)
#giving you a string(output of above code):
'Ben|Wayne'

最后,我们通过astype() 方法将布尔系列类型转换为int:

0    0
1    0
2    1
Name: col1, dtype: int32

另一种方法是使用re 模块中的IGNORECASE 标志,正如@seanbean 在 cmets 中所建议的那样:

from re import IGNORECASE

df['col2']=df['col1'].str.contains('|'.join(bad_list), flags=IGNORECASE).astype(int)

【讨论】:

    猜你喜欢
    • 2022-01-12
    • 1970-01-01
    • 2021-03-20
    • 2022-10-15
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多