英文:
Applying TA-Lib KAMA to DataFrame with groupby
问题
I have a dataframe with stock data sorted by name and date. I'm trying to apply the KAMA (Kaufman Adaptive Moving Average) function to each stock. The function works with the df when I apply it to a new column but not with groupby.
以下是一些虚拟数据和我在Jupyter中尝试过的内容。返回:TypeError: 'Series' objects are mutable, thus they cannot be hashed
import numpy as np
import pandas as pd
import talib as tb
df = pd.DataFrame()
df['NAME'] = ['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B']
df['CLOSE'] = np.random.randint(1,100,df.shape[0])
df['NameNumber']=df.groupby('NAME').cumcount()
cols = ['NAME', 'NameNumber']
df['CN_PK'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
close = df['CLOSE']
df['KAMA'] = tb.KAMA(close, timeperiod = 3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(tb.KAMA(close,timeperiod = 3))
df.head(50)
请注意,这段代码中使用了虚拟数据,并且在应用tb.KAMA
函数时出现了错误。
英文:
I have a dataframe with stock data sorted by name and date. I'm trying to apply the KAMA (Kaufman Adaptive Moving Average) function to each stock. The function works with the df when I apply it to a new column but not with groupby.
Below is some dummy data and with what I've tried so far in Jupyter. It returns: TypeError: 'Series' objects are mutable, thus they cannot be hashed
import numpy as np
import pandas as pd
import talib as tb
df = pd.DataFrame()
df['NAME'] = ['A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A','A',
'A','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B','B',
'B','B']
df['CLOSE'] = np.random.randint(1,100,df.shape[0])
df['NameNumber']=df.groupby('NAME').cumcount()
cols = ['NAME', 'NameNumber']
df['CN_PK'] = df[cols].apply(lambda row: '_'.join(row.values.astype(str)), axis=1)
close = df['CLOSE']
df['KAMA'] = tb.KAMA(close, timeperiod = 3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(tb.KAMA(close,timeperiod = 3))
df.head(50)
答案1
得分: 1
为了完成这个任务,你需要按组提供数据:
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(lambda x: tb.KAMA(x, timeperiod=3))
或者,例如调用一个自定义函数(你可以在其中打印数据并查看它包含的内容):
def f(x):
print(x)
return tb.KAMA(x, timeperiod=3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(f)
英文:
To do this, you need to provide data by group:
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(lambda x: tb.KAMA(x,timeperiod = 3))
or for example calling a custom function (you can print data in it and see what it contains):
def f(x):
print(x)
return tb.KAMA(x,timeperiod = 3)
df['GrpKAMA'] = df.groupby('NAME')['CLOSE'].apply(f)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论