简体   繁体   English

Python Pandas:根据条件创建dataframe

[英]Python Pandas: Create dataframe based on condition

I wanted to create a new dataframe on pandas based on conditions of the current dataframe.我想根据当前 dataframe 的条件在 pandas 上创建一个新的 dataframe。 If the current dataframe is > 1000 rows then make the data frame empty (delete rows).如果当前 dataframe > 1000 行,则将数据框设为空(删除行)。 Otherwise then just use the current dataframe.否则,只需使用当前的 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))

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. np.where需要一个与条件向量形状相同的向量。

Use if else as:使用if else作为:

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

ì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您当前的代码将创建一个数组,如果条件为真,它将采用第一个,如果条件为假,则采用后者

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM