Create Python dataframe conditionally

Viewed 39

I'm trying to create a dataframe based on if col1 and col2 are empty, but col3 has information.
I'm currently using np vectorize, but this creates the dataframe every line versus just a single time.

Here's my code:

def import_check(Col1,Col2, Col3):
    
    if Col1=='' and Col2=='' and  Col3 !='':
        print('being imported')
             
        list=pd.read_csv('mycsv.csv', low_memory=False)
        list.columns=list.columns.str.strip()

        print('List imported')
        
    else:
        
        list= None
       
    return(list)  

The function is called like so:

list=np.vectorize(import_check)(df['calories'], df['duration'],df['size'])

For example if I have 10 lines that match the data will import 10 times. I would like to get my list to read in only once. Is this possible?

If there's anymore information I need to add please let me know

EDIT: Here's an example

data = {
  "calories": ['420', '', ''],
  "duration": ['50', '', '']
  "size": ['30','10','10']

}
df = pd.DataFrame(data)

If you used this data the list dataframe would be imported twice because col1 and 2 are empty but col3 exists with data.

I'd like it to only import once.

1 Answers

you don't want to vectorize your function. If you do that, it'll run for each row in your series. Rather, what you want is to change this condition

if Col1=='' and Col2=='' and  Col3 !='':

Rather than looking at whether the row is zero you could do something like

# this checks to see if you have any non '' in the column
if (df[col1] != '').sum() > 0 and ...
Related