我有一个大约3700行的数据集,需要根据该列删除其中的1628行。数据集如下所示:
compliance day0 day1 day2 day3 day4
True 1 3 9 8 8
False 7 4 8 3 2
True 4 5 0 3 5
True 5 3 9 6 2对于1068行,我希望删除整行if compliance=true。
问题是,我想随机地做这件事;我不想删除前1063行。我试过这个:
for z in range(1629):
rand = random.randint(0,(3783-z)) #subtract z since dataframe shape is shrinking
if str(data.iloc[rand,1]) == 'True':
data = data.drop(balanced_dataset.index[rand])但是,在删除了几行之后,我得到了以下错误:
'labels [2359] not contained in axis'我也试过这个:
data.drop(data("adherence.str.startswith('T').values").sample(frac=.4).index)框架现在是任意挑选的,我只是想让它发挥作用。我得到了以下错误:
'DataFrame' object is not callable任何帮助都将不胜感激!谢谢
发布于 2019-03-02 03:57:40
这对我有用:生成要从其中删除元素的索引列表(在您的例子中是Compliance==True)。然后,根据您想要删除的元素,从列表中随机选择(没有替换)。然后将它们从DataFrame中移除
to_remove = np.random.choice(data[data['Compliance']==True].index,size=1068,replace=False)
data.drop(to_remove)发布于 2019-03-02 04:07:26
将sample与drop结合使用
n = 1068
# Do this first if you haven't already.
# df.compliance = df.compliance.map(pd.eval)
df_dropped = df.drop(df[df.compliance].sample(n=n).index)要使此操作正常,n需要严格小于过滤后的DataFrame。
例如随机删除两行。
df.drop(df[df.compliance].sample(n=2).index)
compliance day0 day1 day2 day3 day4
1 False 7 4 8 3 2
3 True 5 3 9 6 2发布于 2019-03-02 05:08:03
你可以试试:
df_dropped = df.drop(df.loc[df.compliance, :]).sample(n=fraction).index)
https://stackoverflow.com/questions/54955030
复制相似问题