How to create a function (Iteration/Recursion) to run over a dictionary of tuples in Python?

hernanavella

I have a Python dictionary of lists like this one:

d = {'A': [(4, 4, 3), [1, 2, 3, 4, 5]],
     'B': [(2, 1, 2), [5, 4, 3, 2, 1]],
     'C': [(4, 1, 1), [2, 4, 1, 2, 4]]}

I need to create a formula that accesses the elements of the dictionary and, for every value [t, l]:

  • Calculates the mean of t (let's call this m);
  • Takes a random sample s, with replacement and of length len(t), from l;
  • Compares m with the mean of s - True if m is greater than the mean of s, False otherwise;
  • Repeats this process 10,000 times
  • Returns the percentage of times m is greater than the mean of s.

The output should look like:

In [16]: test(d)   
Out[16]: {'A': 0.5, 'B': 0.9, 'C': 0.4}

I think I'm not that far from an answer, this is what I have tried:

def test(dict):
    def mean_diff(dict):
        for k, (v0, v1) in dict.iteritems():
            m = np.mean(v0) > (np.mean(npr.choice(v1, size=(1, len(v0)), replace=True)))
            return ({k: m})
    for k, (v0, v1) in dict.iteritems():
        bootstrap = np.array([means_diff(dict) for _ in range(10000)])
        rank = float(np.sum(bootstrap))/10000
        return ({k: rank})

However, I got:

RuntimeError: maximum recursion depth exceeded while calling a Python object
Cory Kramer

I'd use a list comprehension that essentially selects a random value and compares it to the mean. This will produce a list of True/False. If you take the mean of that, it will be averaging a list of 1's and 0's, so it will give you the aggregate probability.

import numpy as np

d = {'A': [(4, 4, 3), [1, 2, 3, 4, 5]],
     'B': [(2, 1, 2), [5, 4, 3, 2, 1]],
     'C': [(4, 1, 1), [2, 4, 1, 2, 4]]}

def makeRanks(d):
    rankDict = {}
    for key in d:
        tup = d[key][0]
        mean = np.mean(tup)
        l = d[key][1]
        rank = np.mean([mean > np.mean(np.random.choice(l,len(tup))) for _ in range(10000)])
        rankDict[key] = rank
    return rankDict

Testing

>>> makeRanks(d)
{'C': 0.15529999999999999, 'A': 0.72130000000000005, 'B': 0.031899999999999998}

この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。

侵害の場合は、連絡してください[email protected]

編集
0

コメントを追加

0

関連記事

How do I create dictionary from array of tuples?

Run Python function over two DataFrame columns

python - how to create dictionary of dictionary in loop

How to create a dictionary by iterating over a list, with same key multiple values?

How can I loop over the items of a Python dictionary in a random order?

How to iterate over the first n elements of a dictionary in python?

python print dictionary tuples in order grid format

How to nest tuples in Python

How to create a print function in python

Python create combinations of dictionary

How to create a dictionary using python list comprehension from 2 list

How to create a Bootstrap accordion from a nested dictionary in Python?

Python: create sub-dictionary from dictionary

How to create ListIsomorphic instances for tuples and packed types?

How to sort a dictionary of dictionary in python

How to add multiple dictionaries together from a dictionary generator to create single collated python dictionary

How does this function to create a PowerSet in Python works?

Replace the content of dictionary with another dictionary in a function - Python

How to interate over two or more vectors or tuples in julia?

How to iterate over a dictionary and operate with its elements?

How elegantly iterate over list or dictionary

How to iterate over and access individual values in a dictionary

how to iterate over a dictionary from value in an array and store in a new dictionary

How to create dictionary type columns?

How do i actually create/run this class? python

How do I make a function run when a program finishes in Python?

How to group list items into sequential tuples in Python?

In Python how to access elements of tuples using reduce()?

Performantly create a list of python dictionaries by combining a numpy array and a list of tuples

TOP 一覧

  1. 1

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  2. 2

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  3. 3

    CSSのみを使用して三角形のアニメーションを作成する方法

  4. 4

    ドロップダウンリストで選択したアイテムのQComboBoxスタイル

  5. 5

    ZScalerと証明書の問題により、Dockerを使用できません

  6. 6

    PyCharmリモートインタープリターはプロジェクトタブにサイトパッケージのコンテンツを表示しません

  7. 7

    Windows 10でのUSB入力デバイスの挿入/取り外しの検出

  8. 8

    Excel - count multiple words per cell in a range of cells

  9. 9

    PictureBoxで画像のブレンドを無効にする

  10. 10

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  11. 11

    スタート画面にシャットダウンタイルを追加するにはどうすればよいですか?

  12. 12

    Python / SciPyのピーク検出アルゴリズム

  13. 13

    Luaの文字列から特定の特殊文字を削除するにはどうすればよいですか?

  14. 14

    Pythonを使用して、リストからデータを読み取り、特定の値をElasticsearchにインデックス付けするにはどうすればよいですか?

  15. 15

    LinuxでPySide2(Qt for Python)をインストールするQt Designerはどこにありますか?

  16. 16

    goormIDEは、ターミナルがロードするデフォルトプロジェクトを変更します

  17. 17

    QGISとPostGIS(マップポイント(米国の地図上にraduisを使用した緯度と経度)

  18. 18

    MLでのデータ前処理の背後にある直感

  19. 19

    ターミナルから「入力ソースの変更」ショートカットを設定する

  20. 20

    パンダは異なる名前の列に追加します

  21. 21

    同じクラスの異なるバージョンを使用したクラスローディング:java.lang.LinkageError:名前の重複クラス定義を試行しました

ホットタグ

アーカイブ