如何通过匹配我创建的max_min变量中的索引来使用字典创建数据框

时间:2019-07-04 20:52:46

标签: python dataframe

如何使用字典将数据转换为该字典值来自索引的变量max_min的数据帧,我希望该变量可以匹配max_min的索引并创建所需的数据帧。

以下示例代码来自此网站:

https://medium.com/automation-generation/algorithmically-detecting-and-trading-technical-chart-patterns-with-python-c577b3a396ed

Example Image

{% extends 'base.html' %}

{% block title %}Sign Up{% endblock %}

{% block content %}
<h2>Sign up</h2>
<form method="post">
  {% csrf_token %}
  {{ form.as_p }}
  <button type="submit">Sign up</button>
</form>
{% endblock %}

max_min = max_min()

def find_patterns1(max_min):
    pattern1 = defaultdict(列表)

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

2 个答案:

答案 0 :(得分:1)

阅读文档here。取决于您要如何构造DataFrame,可以使用orient参数:

df = pd.DataFrame.from_dict(patterns, orient = 'index')

将为您提供:第一列为字典中的所有键,第二列为值。

也有一个columns参数,您可以在其中将期望的列放在列表中,从而为它们命名。

希望这会有所帮助:))。欢迎来到社区。

答案 1 :(得分:0)

patterns变量是类collections.defaultdict的实例,该类是dict的子类
您可以使用DataFrame.from_dict()函数将字典转换为pandas DataFrame
示例:

df = pd.DataFrame.from_dict(patterns)

注意:欢迎使用stackoverflow,但请尝试修正语法;)