Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/svg/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Pandas 根据条件删除数据帧中的行_Pandas_Dataframe_Delete Row - Fatal编程技术网

Pandas 根据条件删除数据帧中的行

Pandas 根据条件删除数据帧中的行,pandas,dataframe,delete-row,Pandas,Dataframe,Delete Row,假设我有一个数据帧: first_df = pd.DataFrame({"company" : ['abc','def','xyz','lmn','def','xyz'], "art_type": ['300x240','100x600','400x600','300x240','100x600','400x600'], "metrics" : ['imp','rev

假设我有一个数据帧:

first_df = pd.DataFrame({"company" : ['abc','def','xyz','lmn','def','xyz'], 
                                "art_type": ['300x240','100x600','400x600','300x240','100x600','400x600'],
                                "metrics" : ['imp','rev','cpm','imp','rev','cpm'],
                                "value": [1234,23,0.5,1234,23,0.5]})
first_df = first_df.append(first_df)
我想删除列表['lmn','xyz']中所有具有company值的行,并将其存储在另一个数据帧中

company_list = ['lmn', 'xyz']
我试过这个:

deleted_data = first_df[first_df['company'] in company_list] 
这显然不起作用,因为它是列表中的列表。for循环是实现这一点的方法还是有更好的方法

对于循环代码:

deleted_data = pd.DataFrame()
for x in company_list:
    deleted_data = deleted_data.append(first_df[first_df['company']==x])

您可以基于
isin()
进行筛选

deleted_data = first_df.loc[first_df['company'].isin(company_list)]
>>> deleted_data 
  art_type company metrics   value
2  400x600     xyz     cpm     0.5
3  300x240     lmn     imp  1234.0
5  400x600     xyz     cpm     0.5
2  400x600     xyz     cpm     0.5
3  300x240     lmn     imp  1234.0
5  400x600     xyz     cpm     0.5

retained_data = first_df.loc[~first_df['company'].isin(company_list)]
>>> retained_data
  art_type company metrics  value
0  300x240     abc     imp   1234
1  100x600     def     rev     23
4  100x600     def     rev     23
0  300x240     abc     imp   1234
1  100x600     def     rev     23
4  100x600     def     rev     23