Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Drop all drows in python pandas dataframe except

Beginner Pandas Question:

How do I drop all rows except where Ticker = NIVD?

That is, return a dataframe like:

   Sector Ticker  Price
 0 Future   NVID    350
 1 Future   NVID    NaN   

Dataframe Code:

import numpy as np
import pandas as pd
raw_data = {'Sector': [ 'Gas', 'Future', 'Future', 'Gas', 'Beer', 'Future'],
    'Ticker': ['EX', 'NVID', 'ATVI', 'EX', 'BUSCH', 'NVID'],
    'Price': [100, 350, 250, 500, 50, np.NaN]} 
df = pd.DataFrame(raw_data, columns = ['Sector', 'Ticker', 'Price'])
print(df)

So Far I'm playing around with have:

new_df =df[ ~(df[TICKER] == 'NVIDA'):, ] OR

dummy_df=df.loc[:, ~(df == 'NVIDA')]

like image 269
whs2k Avatar asked Jan 19 '26 09:01

whs2k


1 Answers

You are really close.

Use boolean indexing or query:

print(df['Ticker'] == 'NVID')
0    False
1     True
2    False
3    False
4    False
5     True
Name: Ticker, dtype: bool

new_df = df[df['Ticker'] == 'NVID']
print (new_df)
   Sector Ticker  Price
1  Future   NVID  350.0
5  Future   NVID    NaN


new_df = df.query("Ticker == 'NVID'")
print (new_df)
   Sector Ticker  Price
1  Future   NVID  350.0
5  Future   NVID    NaN
like image 133
jezrael Avatar answered Jan 21 '26 02:01

jezrael



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!