回答此问题可获得 20 贡献值,回答如果被采纳可获得 50 分。
<p>我有以下数据帧:</p>
<pre><code>dct = {"A": ["M1", "M1", "M1", "M2", "M2", "M2", "M4", "M4", "M4"],
"B": ["S1", "S1", "S3", "S3", "S4", "S4", "S2", "S2", "S2"],
"C": ["a", "n", "cb", "mk", "bg", "dgd", "rb", "cb", "uyi"],
"D": [3, 2, 5, 8, 10, 1, 2, 2, 7],
"E": [4, 3, 6, 8, 9, 4, 3, 0, 8]}
df = pd.DataFrame(dct)
</code></pre>
<p>df将产生:</p>
<pre><code> A B C D E
0 M1 S1 a 3 4
1 M1 S1 n 2 3
2 M1 S3 cb 5 6
3 M2 S3 mk 8 8
4 M2 S4 bg 10 9
5 M2 S4 dgd 1 4
6 M4 S2 rb 2 3
7 M4 S2 cb 2 0
8 M4 S2 uyi 7 8
</code></pre>
<p>现在,我想向dataframe每行的每个值添加一个值,如下所示:</p>
<pre><code>for i in range(len(df.index)):
row = df.iloc[i, :]
row["F"] = "TEMP_{}".format(i)
</code></pre>
<p>为什么这不起作用</p>
<p>我一直在调查pandas<a href="https://pandas.pydata.org/pandas-docs/stable/user_guide/indexing.html#why-does-assignment-fail-when-using-chained-indexing" rel="nofollow noreferrer">documentation</a>,我知道我可能会得到一份<code>df.iloc[i, :]</code>,但如果可能的话,我想知道这个问题的解决方案</p>
<p>非常感谢您的帮助</p>