python - 如何通过匹配我创建的 max_min 变量中的索引来使用字典创建数据框
问题描述
如何使用字典转换为该字典值来自索引的变量 max_min 的数据帧,我希望它可以匹配 max_min 的索引并创建我需要的数据帧。
下面的示例代码来自这个网站:
def max_min(smoothing=5, window_range=10,parse_dates=[0]):
smooth_prices = df['Price'].rolling(window=smoothing).mean().dropna()
local_max = argrelextrema(smooth_prices.values, np.greater)[0]
local_min = argrelextrema(smooth_prices.values, np.less)[0]
price_local_max_dt = []
for i in local_max:
if (i>window_range) and (i<len(df)-window_range):
price_local_max_dt.append(df.iloc[i-window_range:i+window_range]['Price'].idxmax())
price_local_min_dt = []
for i in local_min:
if (i>window_range) and (i<len(df)-window_range):
price_local_min_dt.append(df.iloc[i-window_range:i+window_range]['Price'].idxmin())
maxima = pd.DataFrame(df.loc[price_local_max_dt])
minima = pd.DataFrame(df.loc[price_local_min_dt])
max_min = pd.concat([maxima, minima]).sort_index()
return max_min
max_min = max_min()
def find_patterns1(max_min):
patterns1 = defaultdict(list)
# Window range is 5 units
for i in range(5, len(max_min)):
window = max_min.iloc[i-5:i]
a = window.iloc[0]
b = window.iloc[1]
c = window.iloc[2]
d = window.iloc[3]
e = window.iloc[4]
# IHS
if c.Price<d.Price and a.Price<c.Price and a.Price<b.Price and a.Price<e.Price and b.Price<e.Price and abs(d.Price-e.Price)<=np.mean([d.Price,e.Price])*0.03:
patterns1['IHS'].append((window.index[0], window.index[-1]))
return patterns1
patterns1 = find_patterns1(max_min)
解决方案
在此处阅读文档。取决于您希望如何构建 DataFrame,您可以使用以下orient
参数:
df = pd.DataFrame.from_dict(patterns, orient = 'index')
将为您提供:字典中所有键的第一列和值的第二列。
还有一个columns
参数,您可以通过将它们放在列表中来为预期的列命名。
希望这可以帮助 :))。欢迎来到社区。
推荐阅读
- python - 用python开发中文会话聊天机器人
- python - Python 通过插值引用数据
- java - DataTable 不是 Liferay 7 上的函数
- apache-kafka - Kafka:为跨分区的字符串生成唯一 ID
- react-native - 导航器更改返回按钮颜色
- reactjs - WebpackError:无法设置未定义的属性“emulateTransitionEnd”
- python - 如何在 python pandas 中获取唯一的行值并返回布尔结果?
- android - Android TimePickerDialog 显示 A. 而不是 AM
- algorithm - Opengl uvw投影,引擎盖下是什么?
- android - Android gradle 多项目依赖解析