达到求和条件后删除行

2024-05-18 23:00:08 发布

您现在位置:Python中文网/ 问答频道 /正文

我想在命中某个值后从数据帧中删除行。你知道吗

示例数据集:

num value 
1   2000
2   3000
3   2000

x = 5000 # my limiter
y = 0 # my bucket for values

# I want to do something like...
for row in df:
    if y <= x:
        y =+ df["Values"]
    elif y > x:
        df.drop(row)
        continue

elif可能没有意义,但它表达了这个想法,我更关心的是解析。我似乎不能在嵌入的if语句中使用df[“Values”]。你知道吗

我得到一个错误:

 ValueError: The truth value of a Series is ambiguous.

这很奇怪,因为我可以在if语句之外单独运行这一行。你知道吗


Tags: 数据示例dfforifbucketvaluemy
2条回答

^{}^{}一起使用:

x = 5000
df = df[df['value'].cumsum() <= x]
print (df)
   num  value
0    1   2000
1    2   3000

细节

print (df['value'].cumsum())
0    2000
1    5000
2    7000
Name: value, dtype: int64

print (df['value'].cumsum() <= x)
0     True
1     True
2    False
Name: value, dtype: bool

由于将整列赋给变量y,因此会收到此错误消息。相反,您只需要指定列value中的值并将其添加到变量中。你知道吗

#print(df)
#num value 
#1   2000
#2   3000
#3   2000
#4   4000
#5   1000

x = 5000 
y = 0 

#iterate over rows
for index, row in df.iterrows():
    if y < x:
        #add the value to y
        y += row["value"]
    elif y >= x:
        #drop rest of the dataframe
        df = df.drop(df.index[index:])
        break

#output from print(df)
#   num  value
#0    1   2000
#1    2   3000

但是如果你只使用pandas内置的cumsum函数,速度会更快。(see jezrael's answer for details

相关问题 更多 >

    热门问题