如何使用字典将数据转换为该字典值来自索引的变量max_min的数据帧,我希望该变量可以匹配max_min的索引并创建所需的数据帧。
以下示例代码来自此网站:
{% 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
答案 0 :(得分:1)
阅读文档here。取决于您要如何构造DataFrame,可以使用orient
参数:
df = pd.DataFrame.from_dict(patterns, orient = 'index')
将为您提供:第一列为字典中的所有键,第二列为值。
也有一个columns
参数,您可以在其中将期望的列放在列表中,从而为它们命名。
希望这会有所帮助:))。欢迎来到社区。 p>
答案 1 :(得分:0)
patterns
变量是类collections.defaultdict
的实例,该类是dict
的子类
您可以使用DataFrame.from_dict()
函数将字典转换为pandas DataFrame
示例:
df = pd.DataFrame.from_dict(patterns)
注意:欢迎使用stackoverflow,但请尝试修正语法;)