从列表中删除包含列表中元素的行

2024-09-30 16:33:15 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个DF:

students = [ ('jack', 34, 'Sydeny' , 'Australia') ,
             ('Riti', 30, 'Delhi' , 'India' ) ,
             ('Vikas', 31, 'Mumbai' , 'India' ) ,
             ('Neelu', 32, 'Bangalore' , 'India' ) ,
             ('John', 16, 'New York' , 'US') ,
             ('Mike', 17, 'las vegas' , 'US')  ]

dfObj = pd.DataFrame(students, columns = ['Name' , 'Age', 'City' , 'Country'], index=['a', 'b', 'c' , 'd' , 'e' , 'f']) 

我有一份清单:

[Vikas, Neelu, Jack]

如何从DF中删除包含此列表中元素的行。我的谷歌搜索只向我展示了如何按列索引或生命等条件删除某个列低于或高于某个整数值


Tags: dfnewjohnusjackindiaaustraliadelhi
2条回答
remove_words = ['Vikas', 'Neelu', 'Jack']

result = dfObj[~dfObj.Name.isin(remove_words)]

# display(result)

   Name  Age       City    Country
a  jack   34     Sydeny  Australia
b  Riti   30      Delhi      India
e  John   16   New York         US
f  Mike   17  las vegas         US

忽略案例

  • 注意'Jack''jack'不同
  • ^{}{}到小写(str.lower
  • 执行布尔检查时,将Name强制转换为带^{}的小写字母。
    • 这将使Name列中的值保持不变
# map the list of words to lowercase
remove_words = list(map(str.lower, ['Vikas', 'Neelu', 'Jack']))

# cast the Name column as lowercase when checking remove_words
result = dfObj[~dfObj.Name.str.lower().isin(remove_words)]

# display(result)
   Name  Age       City Country
b  Riti   30      Delhi   India
e  John   16   New York      US
f  Mike   17  las vegas      US

请使用.str.contains并使用~反向选择

L=['Vikas', 'Neelu', 'Jack']
dfObj[~dfObj.Name.str.contains('|'.join(L))]



 Name  Age       City    Country
a  jack   34     Sydeny  Australia
b  Riti   30      Delhi      India
e  John   16   New York         US
f  Mike   17  las vegas         US

相关问题 更多 >