[英]Looping for creating graphs
我正在尋求一些關於如何最好地自動化循環以創建由dict進行的一些計算的圖形可視化的指導。
我拼湊了以下代碼來創建單個圖形,但需要生成許多相似的圖形(使用不同的變量),而不是多次輸出每個變量(將有100個變量)。
對於單個圖形,我有以下代碼(見下文),其中Calclist是一個字典,而variable1是該字典中的特定列:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
Sets = {}
labels = ['0 - 5','5 - 25','25 - 50','50 - 75','75 - 100']
blocks = [-1,5,25,50,75,100]
for i in Calclist:
out = pd.cut(Calclist[i]['variable1'], bins = blocks)
Sets[i] = (pd.value_counts(out)/Calclist[i]['variable1'].count())*100
df = pd.DataFrame(Sets)
df.reset_index(level=0, inplace=True)
df.rename(index = str, columns = {'index':'blocks'}, inplace=True)
ax = df.plot.bar(title='One iteration - works well')
ax.set_xlabel("x-axis label")
ax.set_ylabel("y-axis label")
ax.set_xticklabels(labels, rotation=45)
到目前為止,這很好 - 這是代碼將產生的:
我真正想做的是遍歷variable1(到variable2,variable3,.....)。
我嘗試了幾件事,並認為我很接近但可能缺少一些基本的東西。
具體來說,我嘗試嵌套另一個循環,使用“參數”迭代一系列,其中包含我對可視化感興趣的變量名稱:
Sets = {}
labels = ['0 - 5','5 - 25','25 - 50','50 - 75','75 - 100']
blocks = [-1,5,25,50,75,100]
Parameter = pd.Series("variable1","variable2")
for j in Parameter:
for i in Calclist:
out = pd.cut(Calclist[i][Parameter[j]], bins = blocks)
Sets[i] = (pd.value_counts(out)/Calclist[i]
[Parameter[j]].count())*100
但是我收到以下錯誤:
TypeError: Index(...) must be called with a collection of some kind,
'powertotal_total' was passed
任何和所有建議都非常感謝。
你不能以這種方式迭代大熊貓系列。 嘗試
for j in ["variable1","variable2"]:
或者一些變化
編輯:或查找如何迭代大熊貓系列http://pandas.pydata.org/pandas-docs/stable/generated/pandas.Series.iteritems.html
您的錯誤消息是由初始化Parameters
的方式引起的:
parameter = pd.Series('variable1', 'variable2')
...
TypeError: Index(...) must be called with a collection of some kind,
'variable2' was passed
您必須將類似數組,字典或標量值傳遞給pd.Series
。 此外,迭代Parameters
將返回其值。 最后,您應該為每個parameter
初始化Sets
:
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
labels = ['0 - 5','5 - 25','25 - 50','50 - 75','75 - 100']
blocks = [-1,5,25,50,75,100]
Parameters = pd.Series(['variable1', 'variable2'])
for parameter in Parameters:
Sets = {}
for i in Calclist:
out = pd.cut(Calclist[i][parameter], bins = blocks)
Sets[i] = (pd.value_counts(out)/Calclist[i][parameter].count())*100
df = pd.DataFrame(Sets)
df.reset_index(level=0, inplace=True)
df.rename(index=str, columns={'index': 'blocks'}, inplace=True)
ax = df.plot.bar(title=parameter)
ax.set_xlabel("x-axis label")
ax.set_ylabel("y-axis label")
ax.set_xticklabels(labels, rotation=45)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.