12

各数値のパーセンテージの変化を計算しようとしている価格のリストがあります。との差を計算しました

    prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]

    def f():
        for i in range(len(prices)):
            print(prices[i]-prices[i-1])

次のような違いを返します

    2.1
    -0.8
    -0.5
    ...

パーセンテージの変化が ((i-(i-1))/(i-1) *100 になることはわかっていますが、それをスクリプトに組み込む方法がわかりません。

4

3 に答える 3

20

Python(http://pandas.pydata.org/)のpandasライブラリに触れたことがない場合は、ぜひチェックしてください。

これを行うのは次のように簡単です。

import pandas as pd
prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]

price_series = pd.Series(prices)
price_series.pct_change()
于 2013-01-04T21:41:36.810 に答える
15

これを試して:

prices = [30.4, 32.5, 31.7, 31.2, 32.7, 34.1, 35.8, 37.8, 36.3, 36.3, 35.6]

for a, b in zip(prices[::1], prices[1::1]):
    print 100 * (b - a) / a

編集:これをリストとして必要な場合は、次のようにすることができます。

print [100 * (b - a) / a for a, b in zip(prices[::1], prices[1::1])]
于 2012-10-03T00:08:38.183 に答える