Home > other >  Python Pandas: Create dataframe based on condition
Python Pandas: Create dataframe based on condition

Time:07-29

I wanted to create a new dataframe on pandas based on conditions of the current dataframe. If the current dataframe is > 1000 rows then make the data frame empty (delete rows). Otherwise then just use the current dataframe. Below is my code that is having an error:

DF_NEW = np.where(len(DF)>1000, pd.DataFrame(DF[0:0]), pd.DataFrame(DF))

CodePudding user response:

You should use:

DF_NEW = pd.DataFrame(columns=DF.columns) if len(DF) > 1000 else DF.copy()

np.where need a vector with the same shape of your condition vector.

CodePudding user response:

Use if else as:

if len(DF)>1000:
    DF_NEW = pd.DataFrame(columns=DF.columns)
else:
    DF_new = DF.copy()

CodePudding user response:

ìf len(df) > 1000:
    for label in df.columns: 
        df.pop('label')
elif len(df) <= 1000:
    pass

your current code will make an array where, if the condition is True, it will take the first, and if condition is False, the latter

  • Related