直接来自教程,即使在阅读完文档后我也无法理解。
In [14]: df = DataFrame({'one' : Series(randn(3), index=['a', 'b', 'c']),
....: 'two' : Series(randn(4), index=['a', 'b', 'c', 'd']),
....: 'three' : Series(randn(3), index=['b', 'c', 'd'])})
....:
In [15]: df
Out[15]:
one three two
a -0.626544 NaN -0.351587
b -0.138894 -0.177289 1.136249
c 0.011617 0.462215 -0.448789
d NaN 1.124472 -1.101558
In [16]: row = df.ix[1]
In [17]: column = df['two']
In [18]: df.sub(row, axis='columns')
Out[18]:
one three two
a -0.487650 NaN -1.487837
b 0.000000 0.000000 0.000000
c 0.150512 0.639504 -1.585038
d NaN 1.301762 -2.237808
为什么第二行变为0?它是sub
- 用0建立吗?
此外,当我使用row = df.ix[0]
时,整个第二列变为NaN
。为什么呢?
答案 0 :(得分:5)
sub
表示减去,所以让我们来看看:
In [44]:
# create some data
df = pd.DataFrame({'one' : pd.Series(np.random.randn(3), index=['a', 'b', 'c']),
'two' : pd.Series(np.random.randn(4), index=['a', 'b', 'c', 'd']),
'three' : pd.Series(np.random.randn(3), index=['b', 'c', 'd'])})
df
Out[44]:
one three two
a -1.536737 NaN 1.537104
b 1.486947 -0.429089 -0.227643
c 0.219609 -0.178037 -1.118345
d NaN 1.254126 -0.380208
In [45]:
# take a copy of 2nd row
row = df.ix[1]
row
Out[45]:
one 1.486947
three -0.429089
two -0.227643
Name: b, dtype: float64
In [46]:
# now subtract the 2nd row row-wise
df.sub(row, axis='columns')
Out[46]:
one three two
a -3.023684 NaN 1.764747
b 0.000000 0.000000 0.000000
c -1.267338 0.251052 -0.890702
d NaN 1.683215 -0.152565
所以可能令你感到困惑的是,当你指定列数时,会发生什么?&#39;作为操作的轴。我们从每一行中减去第二行的值,这就解释了为什么第二行现在变成了全部0#s。您已经通过的数据是一系列的,我们正在对齐列,因此实际上我们正在对齐列名称,这就是它按行执行的原因<\ n \ n / p>
In [47]:
# now take a copy of the first row
row = df.ix[0]
row
Out[47]:
one -1.536737
three NaN
two 1.537104
Name: a, dtype: float64
In [48]:
# perform the same op
df.sub(row, axis='columns')
Out[48]:
one three two
a 0.000000 NaN 0.000000
b 3.023684 NaN -1.764747
c 1.756346 NaN -2.655449
d NaN NaN -1.917312
那么为什么我们现在有一个包含所有NaN
值的列?这是因为当您使用NaN
执行任何运算符函数时,结果为NaN
In [55]:
print(1 + np.NaN)
print(1 * np.NaN)
print(1 / np.NaN)
print(1 - np.NaN)
nan
nan
nan
nan
答案 1 :(得分:2)
正在做的是从其列中的所有值中减去第二行中的每个值。也就是说,它取位置<div class="tile-wrapper-test">
<div id="category-text">
<p class="category-content">Smartphones / software</p>
</div>
<div class="tile-image-test">
<a href="#"><img src="images/wp10.jpg" class="tile-image" name="title" /></a>
</div>
<div class="title-text-test">
<a href="#" class="title-text">text text text text text text</a>
</div>
<div id="date-time-text">
<p class="date-time">3 minutes ago.</p>
</div>
</div>
$(document).ready(function () {
$(".title-text-test").each(function () {
imageWidth = $('.tile-image-test').width();
$(".title-text-test").width(imageWidth);
if (imageWidth > 250) {
$(".title-text-test").addClass('clr');
}
});
});
的值并从列#34中的所有值中减去它;一个&#34 ;;它取位置("b", "one")
的值并从列#34中的所有值中减去它;两个&#34 ;;它取poisiton ("b", "two")
的值,并从列#34; 3&#34;中的所有值中减去它。因此,例如,("b", "three")
中的结果为("c", "one")
。行中的所有值&#34; b&#34;是零,因为这是你要减去的行,所以在那一行你从它自己减去它,给出零。
至于问题的第二部分,如果选择第一行,则它包含一个NaN。因此,减法从第二列中的所有值中减去NaN,这也将它们全部变为NaN(因为任何减去NaN的东西都是NaN)。