Pandas 篩選和刪除目標值所在的行的實現

1.篩選出目標值所在行 

單列篩選

# df[列名].isin([目標值])對當前列中存在目標值的行會返回True,不存在的返回False
df[df[列名].isin([目標值])]

練習案例 

import pandas as pd
 
df_bom_data = pd.DataFrame([['A123',1200,5],
                            ['B456',550,2],
                            ['C437',500,10],
                            ['D112',621,7],
                            ['E211',755,11],
                            ['F985',833,8]
                            ],columns=['Material','Price','Quantity'])
 
df_material_shortage_data = pd.DataFrame([['A123','2022/6/21',100],
                                          ['B456','2022/6/22',120],
                                          ['C437','2022/6/23',250]
                                          ],columns=['Material','Schedule','LT'])
# 篩選出df_bom_data表中隻包含df_material_shortage_data表中Material的行記錄
df_bom_data = df_bom_data[df_bom_data['Material'].isin(df_material_shortage_data['Material'])]

df_bom_data

df_material_shortage_data 

df_bom_data(處理後)

多列篩選

# 同時滿足用&連接,或的話用 | 連接
df[df[列名].isin([目標值]) & df[列名].isin([目標值])]
df[df[列名].isin([目標值]) | df[列名].isin([目標值])]

練習案例 

import pandas as pd
 
df = pd.DataFrame([['L123','A',0],
                   ['L456','A',1],
                   ['L437','C',0],
                   ['L112','B',1],
                   ['L211','A',0],
                   ['L985','B',1]
                  ],columns=['Material','Level','Passing'])
# 篩選出指定列都有目標值的行
res1 = df[df['Level'].isin(['A','C']) & df['Passing'].isin([0])]
# 篩選出至少有一列有目標值的行
res2 = df[df['Level'].isin(['A','C']) | df['Passing'].isin([0])]

df

res1

res2 

2.刪除目標值所在的行

練習案例

import pandas as pd
import numpy as np
 
df_bom_data = pd.DataFrame([['A123',1200,5],
                            ['B456',np.nan,np.nan],
                            ['C437',500,10]
                            ],columns=['Material','Price','Quantity'])
 
df_material_shortage_data = pd.DataFrame([['A123','2022/6/21',100],
                                          ['B456','2022/6/22',120],
                                          ['C437','2022/6/23',250]
                                          ],columns=['Material','Schedule','LT'])
 
# 篩選出df_bom_data中'Price'和'Quantity'兩列字段的值都為空(nans)的行
df_isnull_bom_data = df_bom_data[pd.isnull(df_bom_data[df_bom_data.columns.tolist()[1:]]).all(axis=1)]
 
# df_material_shortage_data表刪除all_isnull_df_bom_data表中的Material
df_material_shortage_data = df_material_shortage_data[~df_material_shortage_data['Material'].isin(df_isnull_bom_data['Material'])]

df_bom_data

df_material_shortage_data

df_isnull_bom_data 

df_material_shortage_data(處理後)

擴展補充案例:刪除列為指定值所在的行

import pandas as pd
 
df = pd.DataFrame([[0,1,2,3],
                  [4,5,6,7],
                  [8,9,10,11]
                  ],columns=['A','B','C','D'])
 
# 通過重新取值,數據篩選後重新賦值,達到刪除列為指定值的行數據
# 刪除A列中值為0的那一行記錄
df = df[df['A'] != 0]

df

df(處理後) 

 到此這篇關於Pandas 篩選和刪除目標值所在的行的實現的文章就介紹到這瞭,更多相關Pandas 篩選和刪除目標值所在的行內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: