2

数字の不完全なリストを完成させようとしていますが、それを行うためのpythonicな方法が見つかりませんでした。1 から 31 までの一連の日があり、それぞれの日には float 値があります。

#dictionnary{day: value}
monthvalues = {1: 1.12, 2: 3.24, 3: 2.23, 5: 2.10, 7: 4.97} etc.. to 31st day

しかし、私のデータは不完全で、何日か欠落しています! したがって、不足している画像を次のように数学的に埋めたいと思います。

サンプル月 1:

{16: 2.00, 18: 4.00}
#==> I want to add to the dictionnary 17: 3.00

サンプル月 2:

{10: 2.00, 14: 4.00}
#==> I want to add to the dictionnary 11: 2.25, 12: 2.50, 13: 2.75

単純に聞こえますが、不完全なSQLデータベースから処理する行が数百万あり、今のところfor xrange()ループでかなり迷っています...数学ライブラリにメソッドがあるかもしれませんが、見つかりませんでした。

ご協力いただきありがとうございます!

編集: 数値を補間したいのですが、私が知る限り、これらの種類の数学関数を持っているのは numpy/scipy だけで、numpy/scipy と互換性のない Pypy を使用しています。

4

3 に答える 3

1

必要なのは、単純なループと古き良きプログラミングロジックだけです。このロジックの1つの注意点は、それが機能するために開始番号と終了番号が必要なことです。それがあなたのデータにとって意味があるかどうかはわかりませんが、補間にはそれが必要です。

設定:

# Keeps track of the last "seen" day
lastday=0

# Default 1st day if missing
if 1 not in monthvalues:
  monthvalues[1] = 1.23 #you need a default

# Default 31st day if missing
if 31 not in monthvalues:
  monthvalues[31] = 1.23 #you need a default

処理:

# Loop from 1 to 31
for thisday in range(1,32):

  # If we do not encounter thisday in the monthvalues, then skip and keep looping
  if thisday not in monthvalues:
    continue

  # How far ago was the last day seen?
  gap = thisday - lastday

  # If the last day was more than 1 ago, it means there is at least one day amis
  if gap > 1:

    # This is the amount of the last "seen" day
    last_amt = monthvalues[lastday]

    # this is the difference between the current day and the last day
    diff = monthvalues[thisday] - last_amt

    # This is how much you want to interpolate per day in-between
    amt_per_day = diff/gap

    # there is a gap of missing days, let's fill them
    # Start at 1 because we start at the day after the last seen day
    for n in range(1, gap):

      # Fill the missing days with an interpolated value
      monthvalues[lastday+n] = last_amt + amt_per_day * n

  # For the next iteration of the loop, this is the last seen day.
  lastday = thisday
于 2012-10-19T21:53:09.410 に答える
0

scipy の補間メソッドを使用するのが賢い方法だと思います

まず、データを操作しやすい形式に変換します。

monthvalue = {1: 1.12, 2: 3.24, 3: 2.23, 5: 2.10, 7: 4.97, 6: 3.10, 10: 3.3}
X = sorted(monthvalue.keys())
Y = [monthvalue[x] for x in X]

次に、線形補間関数を作成し、中間値を出力します

# interpolate function
f = interp1d(X, Y, kind='linear')

x_new = range(X[0], X[-1]+1, 1)
for x in x_new:
    print "%s: %s" % (x, f(x))

結果:

1: 1.12
2: 3.24
3: 2.23
4: 2.165
5: 2.1
6: 3.1
7: 4.97
8: 4.41333333333
9: 3.85666666667
10: 3.3
于 2016-11-15T03:24:39.787 に答える