How can I make this python code more efficient?

Dougie Fresh

I realize this is an incredibly inefficient way to code this, so I'm hoping someone will have suggestions on a more efficient method.

Essentially I'm trying to create a column ("freq") with values of 0 for NA and "Nothing" objects and 1 otherwise. Sample df:

i   obj           freq

0.  Nothing        0
1.  Something      1
2.  NaN            0
3.  Something      1


for i in range(0,len(df)):
  if str(df["obj"].iloc[i]) == "Nothing" or str(df["obj"].iloc[i]) == NaN:
    d["freq"].iloc[i] = 0
  else:
    df["freq"].iloc[i] = 1
Matthew Borish

You can use np.where()

import pandas as pd 
import numpy as np

df = pd.DataFrame({'obj': {0: 'Nothing', 1: 'Something', 2: np.nan, 3: 'Something'}})

df['freq'] = np.where((df['obj'] == 'Nothing') | (df['obj'].isnull()), 0, 1)

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

How can I make this Python code more efficient

How can I make a code more efficient and shorter?

How can I make this C# code more efficient?

How can I make my pandas code more efficient?

How can I refactor this code snippet to make it more efficient?

How can I use iteration to make this vbnet code more efficient?

How can I concatenate my code properly and make this more efficient?

How can I optimize this VBA code to make it more efficient and faster?

Why is this Python code so slow? How can I make it more efficient?

How can i make this script more efficient?(Python)

How can I make this loop more efficient?

How can I make this more efficient in Android?

How can I write this code more efficient?

How would I make this more efficient? (python)

Can I use classes or lists to make my code more efficient?

Can I make this Clojure code (scoring a graph bisection) more efficient?

How can I make my code more efficient in R - It's to repetitive

android - SQL database, how can I make my code more efficient

How can I make this PyTorch tensor (B, C, H, W) tiling & blending code simpler and more efficient?

I made a basic python calculator, how can I make it more efficient

How do I make this matching list code more efficient?

How would I make this code more compact/efficient?

Any idea how I could make this code more efficient?

Python: How can I make my implementation of bubble sort more time efficient?

How can I make my trie more efficient?

How can I make this PyTorch heatmap function faster and more efficient?

How can I make this search query more efficient?

How can I make a recursive search for longest node more efficient?

How can I make this more efficient path finding?