Liebe Mein Anfänger für Python ist eine harte Prüfung unterziehen ...Python Pandas Funktion mit zwei Argumenten rollen
Ich brauche eine Funktion in einem Rollfenster einer festen Länge berechnen (sagen wir mal: 5). Die Funktion benötigt zwei Parameter. Ich bin mir der Antwort sehr bewusst, here die fast identisch ist, aber ich bekomme immer Fehler.
Mein Code ist einfach:
import numpy as np
import pandas as pd
import scipy as sp
import scipy.stats
df = pd.DataFrame({'A' : np.arange(20), 'B' : np.random.randint(0,20,20)})
def my_tau2(idx):
x = df.loc[idx, 'A'].astype('float')
y = df.loc[idx, 'B'].astype('float')
return scipy.stats.mstats.kendalltau(x, y)[0] ## breaks without this [0]
pd.rolling_apply(np.arange(len(df), dtype = np.dtype('int16')), 5, my_tau2)
Und ich bekomme immer folgende Fehlermeldung:
enter code
File "<ipython-input-6-d6cbc608d2f0>", line 7, in <module>
pd.rolling_apply(np.arange(len(df), dtype = np.dtype('int16')), 5, my_tau2)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\stats\moments.py", line 584, in rolling_apply
kwargs=kwargs)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\stats\moments.py", line 240, in ensure_compat
result = getattr(r, name)(*args, **kwds)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\window.py", line 863, in apply
return super(Rolling, self).apply(func, args=args, kwargs=kwargs)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\window.py", line 621, in apply
center=False)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\window.py", line 560, in _apply
result = calc(values)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\window.py", line 555, in calc
return func(x, window, min_periods=self.min_periods)
File "D:\Users\502031217\AppData\Local\Continuum\Anaconda3\lib\site-packages\pandas\core\window.py", line 618, in f
kwargs)
File "pandas\algos.pyx", line 1831, in pandas.algos.roll_generic (pandas\algos.c:51581)
TypeError: a float is required
Ich habe mit, dass zu kämpfen und ich werde verrückt. Meine Modulversionen sind:
- numpy: 1.11.0
- scipy: 0.17.1
- Pandas: 0.18.1
- Python: 3.5.1
Irgendwelche Hinweise w.r.t. Wie man das auf eine andere Weise korrigiert oder berechnet, ist von ganzem Herzen willkommen.
Danke, Marjan! Diese [0] bei der von scipy.stats.mstats.kendalltau (x, y) ist die magische Zutat. Ich habe den Code aktualisiert, damit er jetzt funktioniert. Tatsächlich sind keine weiteren Änderungen erforderlich. Ich denke, es hat nicht funktioniert, weil pandas/numpy den Typ des Rückgabeobjekts nicht erkennen konnte (scipy.stats.mstats_basic.KendalltauResult). – rpl
Ich denke, wir waren gleichzeitig Lehrer und Schüler! Das ist die Schönheit von Stackoverflow! Froh, dass ich geholfen habe. –