DataFrame型の変数に対して、変数.diff(変数.diff - x, axis="0 or 1")
と指定で
行間または列間の差を計算したDataFrameが作成
第1引数が正の場合は前の行との差、負の場合は後の行との差
axis
は0
の場合が行(横)方向、1
の場合が列(縦)方向です。
1 |
<span role="presentation"><span class="cm-keyword">import</span> <span class="cm-variable">numpy</span> <span class="cm-keyword">as</span> <span class="cm-variable">np</span></span> |
1 |
<span role="presentation"><span class="cm-keyword">import</span> <span class="cm-variable">pandas</span> <span class="cm-keyword">as</span> <span class="cm-variable">pd</span></span> |
1 |
<span role="presentation"><span class="cm-variable">np</span>.<span class="cm-property">random</span>.<span class="cm-property">seed</span>(<span class="cm-number">0</span>)</span> |
1 |
<span role="presentation"><span class="cm-variable">columns</span> = [<span class="cm-string">"apple"</span>, <span class="cm-string">"orange"</span>, <span class="cm-string">"banana"</span>, <span class="cm-string">"strawberry"</span>, <span class="cm-string">"kiwifruit"</span>]</span> |
1 |
<span role="presentation"></span> |
1 |
<span role="presentation"><span class="cm-comment"># DataFrameを生成し、列を追加</span></span> |
1 |
<span role="presentation"><span class="cm-variable">df</span> = <span class="cm-variable">pd</span>.<span class="cm-property">DataFrame</span>()</span> |
1 |
<span role="presentation"><span class="cm-keyword">for</span> <span class="cm-variable">column</span> <span class="cm-keyword">in</span> <span class="cm-variable">columns</span>:</span> |
1 |
<span role="presentation"> <span class="cm-variable">df</span>[<span class="cm-variable">column</span>] = <span class="cm-variable">np</span>.<span class="cm-property">random</span>.<span class="cm-property">choice</span>(<span class="cm-builtin">range</span>(<span class="cm-number">1</span>, <span class="cm-number">11</span>), <span class="cm-number">10</span>)</span> |
1 |
<span role="presentation"><span class="cm-variable">df</span>.<span class="cm-property">index</span> = <span class="cm-builtin">range</span>(<span class="cm-number">1</span>, <span class="cm-number">11</span>)</span> |
1 |
<span role="presentation"></span> |
1 |
<span role="presentation"><span class="cm-comment"># dfの各行について、2行後の行との差を計算したDataFrameをdf_diffに代入</span></span> |
1 2 3 |
<span role="presentation"><span class="cm-variable">df_diff</span>=<span class="cm-variable">df</span>.<span class="cm-property">diff</span> <span class=" CodeMirror-matchingbracket">(</span><span class="cm-operator">-</span><span class="cm-number">2</span>,<span class="cm-variable">axis</span> = <span class="cm-number">0</span><span class=" CodeMirror-matchingbracket">) #第一引数がマイナスの場合は下、右方向へ処理 第一引数がプラスの場合は上、左方向へ処理</span></span> |
1 |
</code><code> |
1 |
<span role="presentation"><span class="cm-builtin">print</span>(<span class="cm-variable">df</span>)</span> |
1 |
<span role="presentation"><span class="cm-builtin">print</span>(<span class="cm-variable">df_diff</span>)</span> |
コメントを残す