<p>考虑您的<code>df</code></p>
<pre><code>data = {
'Animal': ['cat', 'dog', 'dog', 'cat', 'bird', 'dog', 'cow'],
'Noise': ['muh', 'miau', 'wuff', 'piep', 'piep', 'miau', 'muh']
}
df = pd.DataFrame(data)
</code></pre>
<p>我会用一个最初计算过的字典来定义什么是匹配。然后,使用<code>map</code>转换并测试是否相等。之后,我将使用<code>assign</code>生成所需的列。在</p>
^{pr2}$
<hr/>
<p>回答您的具体问题:<br/>
循环中的<code>row</code>不再附加到数据帧。因此,当您使用<code>True</code>或<code>False</code>分配给数据帧时,您将无法访问刚刚从<code>row</code>设置的值。相反,请使用<code>df.get_value</code></p>
<pre><code>for row in df.itertuples():
if row.Animal == 'cat' and row.Noise == 'miau':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'dog' and row.Noise == 'wuff':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'bird' and row.Noise == 'piep':
df.set_value(index=row.Index, col='Match', value=True)
elif row.Animal == 'cow' and row.Noise == 'muh':
df.set_value(index=row.Index, col='Match', value=True)
# This should work
if df.get_value(index=row.Index, col='Match') is True:
df.set_value(index=row.Index, col='Comment', value='yeah')
</code></pre>