擅长:python、mysql、java
<p>好的,如果要在<code>df</code>中设置值,则需要跟踪<code>index</code>值。</p>
<p><strong><em>选项1</em></strong><br/>
使用<code>itertuples</code></p>
<pre><code># keep in mind `row` is a named tuple and cannot be edited
for line, row in enumerate(df.itertuples(), 1): # you don't need enumerate here, but doesn't hurt.
if row.Qty:
if row.Qty == 1 and row.Price == 10:
df.set_value(row.Index, 'Buy', 1)
</code></pre>
<p><strong><em>选项2</em></strong><br/>
使用<code>iterrows</code></p>
<pre><code># keep in mind that `row` is a `pd.Series` and can be edited...
# ... but it is just a copy and won't reflect in `df`
for idx, row in df.iterrows():
if row.Qty:
if row.Qty == 1 and row.Price == 10:
df.set_value(idx, 'Buy', 1)
</code></pre>
<p><strong><em>选项3</em></strong><br/>
使用带<code>get_value</code>的直上循环</p>
<pre><code>for idx in df.index:
q = df.get_value(idx, 'Qty')
if q:
p = df.get_value(idx, 'Price')
if q == 1 and p == 10:
df.set_value(idx, 'Buy', 1)
</code></pre>