我想计算数据框中的值,按带有 iterrows 的行进行计算,如下所示:
df = pd.DataFrame([ list( range( 0, 6)) + [np.NaN] * 5,
list( range(10,16)) + [np.NaN] * 5,
list( range(20,26)) + [np.NaN] * 5,
list( range(30,36)) + [np.NaN] * 5])
for (index, row) in df.iterrows():
df.loc[ index, 6: 11] = row[ 1: 6] - row [ 0]
为什么 df 没有更新?
我什至尝试将 row[ 1: 6] - row [ 0]
替换为 df.loc[index, 1: 6] - df.loc[index, 0]
它不起作用。这是一个微不足道的错误还是我没有掌握更微妙的概念?还有更高效的东西吗?
最佳答案
使用 loc
进行 Pandas 赋值会在赋值之前进行索引对齐。您的列名称将在此处错位。这样做:
for (index, row) in df.iterrows():
df.loc[ index, 6: 11] = (row[ 1: 6] - row [ 0]).values
df
Out[23]:
0 1 2 3 4 5 6 7 8 9 10
0 0 1 2 3 4 5 1.0 2.0 3.0 4.0 5.0
1 10 11 12 13 14 15 1.0 2.0 3.0 4.0 5.0
2 20 21 22 23 24 25 1.0 2.0 3.0 4.0 5.0
3 30 31 32 33 34 35 1.0 2.0 3.0 4.0 5.0
文档 here欲了解更多信息:
Warning pandas aligns all AXES when setting Series and DataFrame from .loc, .iloc and .ix. This will not modify df because the column alignment is before value assignment.
关于python-3.x - 使用 iterrow 更新数据框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42770080/