擅长:python、mysql、java
<p>由于将整列赋给变量<code>y</code>,因此会收到此错误消息。相反,您只需要指定列<code>value</code>中的值并将其添加到变量中。你知道吗</p>
<pre><code>#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
</code></pre>
<p>但是如果你只使用pandas内置的<code>cumsum</code>函数,速度会更快。(<a href="https://stackoverflow.com/a/48850687/8881141">see jezrael's answer for details</a>)</p>