Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Fastest Way to Zero dataframe/column in Python Pandas

Tags:

python

pandas

Is there a faster way to zero out a pandas dataframe column than iterating through the dataframe like this (where A, B and C are the Column names):

while x < Framelength
   dg.iloc[x, A] = 0
   dg.iloc[x, B] = 0
   dg.iloc[x, C] = 0
   x+=1

I'm okay with zeroing out the entire dataframe if that would be faster

like image 703
DyTech Avatar asked Aug 19 '20 02:08

DyTech


3 Answers

Check with

cols=[...]
df.loc[:, cols]=0
like image 135
BENY Avatar answered Oct 09 '22 15:10

BENY


You can zero out the entire dataframe:

df[df.columns] = 0

or specify a list (iterable) of columns:

cols = list("ABC")
df[cols] = 0
like image 26
anon01 Avatar answered Oct 09 '22 15:10

anon01


For zeroing all rows in a column by calling the column's name you could do something like:

df["A"] = 0
df["B"] = 0

If you want to zero the entire DataFrame though I believe something like this should be quite efficient:

for c in df:
    df[c].values[:] = 0
like image 1
Marcos Tidball Avatar answered Oct 09 '22 16:10

Marcos Tidball