在Python/Pandas中,如何根据存储在列表中的条件筛选数据框?

huangapple go评论56阅读模式
英文:

In python/pandas, how to filter the dataframe whice condition stored in list

问题

在Python/Pandas中,如何使用存储在列表中的条件来过滤DataFrame?
以下代码ori_data[ori_data['category'] in ['a','d','f']]无法工作

import pandas as pd
ori_data = pd.DataFrame({'category':['a','a','b','c','d','f']})
filtered_data = ori_data[ori_data['category'].isin(['a','d','f'])]
英文:

in python/pandas, how to filter the dataframe the condition stored in list ?
Below code ori_data[ori_data['category'] in ['a','d','f']] can't work

import pandas as pd
ori_data = pd.DataFrame({'category':['a','a','b','c','d','f']})
filtered_data = ori_data[ori_data['category'] in ['a','d','f']]

答案1

得分: 1

如果我理解你的问题正确,你只需要使用.isin()

import pandas as pd

ori_data = pd.DataFrame({'category': ['a', 'a', 'b', 'c', 'd', 'f']})
filtered_data = ori_data[ori_data['category'].isin(['a', 'd', 'f'])]
英文:

If I understood your question correctly, all you need to do is use .isin().

import pandas as pd

ori_data = pd.DataFrame({'category': ['a', 'a', 'b', 'c', 'd', 'f']})
filtered_data = ori_data[ori_data['category'].isin(['a', 'd', 'f'])]

huangapple
  • 本文由 发表于 2023年5月29日 11:57:56
  • 转载请务必保留本文链接:https://go.coder-hub.com/76354598.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定