我无法理解代码的具体部分

时间:2014-09-26 03:08:56

标签: python python-2.7 ipython

本练习的目标是生成此页面中的图表:(http://www.realclearpolitics.com/epolls/2012/president/us/general_election_romney_vs_obama-1171.html

用于生成这样的图的数据存储为XML页面,其URL如下: http://charts.realclearpolitics.com/charts/[id].xml 这里,[id]是一个唯一的整数,位于显示图形的页面的URL的末尾。奥巴马 - 罗姆尼竞选的身份是1171:

import re 

def get_poll_xml(poll_id):
    url ="http://charts.realclearpolitics.com/charts/%i.xml" %int(poll_id)
    return requests.get(url).text

def _strip(s): # function to remove characters
    return re.sub(r'[\W_]+', '', s)

def plot_colors(xml):
    '''
    Given an XML document like the link above, returns a python dictionary
    that maps a graph title to a graph color.

    Both the title and color are parsed from attributes of the <graph> tag:
    <graph title="the title", color="#ff0000"> -> {'the title': '#ff0000'}
   '''
    dom = web.Element(xml)
    result = {}
    for graph in dom.by_tag('graph'):
        title = _strip(graph.attributes['title'])
        result[title] = graph.attributes['color']
    return result

def rcp_poll_data(xml):
    """ 
     A pandas DataFrame with the following columns:
    date: The date for each entry
    title_n: The data value for the gid=n graph 

    This DataFrame should be sorted by date

    Example
     -------
     Consider the following simple xml page:

   <chart>
   <series>
   <value xid="0">1/27/2009</value>
   <value xid="1">1/28/2009</value>
   </series>
  <graphs>
  <graph gid="1" color="#000000" balloon_color="#000000" title="Approve">
  <value xid="0">63.3</value>
  <value xid="1">63.3</value>
  </graph>
  <graph gid="2" color="#FF0000" balloon_color="#FF0000" title="Disapprove">
  <value xid="0">20.0</value>
  <value xid="1">20.0</value>
  </graph>
  </graphs>
  </chart>

  Given this string, rcp_poll_data should return
  result = pd.DataFrame({'date': pd.to_datetime(['1/27/2009', '1/28/2009']), 
                       'Approve': [63.3, 63.3], 'Disapprove': [20.0, 20.0]})
  """
    dom = web.Element(xml)
    result = {}        

    dates = dom.by_tag('series')[0]    
    dates = {n.attributes['xid']: str(n.content) for n in dates.by_tag('value')}

    keys = dates.keys()
    result['date'] = pd.to_datetime([dates[k] for k in keys]) 

    for graph in dom.by_tag('graph'):
        name = graph.attributes['title']
        data = {n.attributes['xid']: float(n.content) if n.content else np.nan for n   in graph.by_tag('value') }
        keyl = data.keys()    
        result[name] = [data[k]for k in keyl]

    result = pd.DataFrame(result)   
    result = result.sort(columns=['date'])

    return result

def poll_plot(poll_id):
    xml = get_poll_xml(poll_id)
    data = rcp_poll_data(xml)
    colors = plot_colors(xml)

    #remove characters like apostrophes
    data = data.rename(columns = {c: _strip(c) for c in data.columns})

    #normalize poll numbers so they add to 100%    
    norm = data[colors.keys()].sum(axis=1) / 100    
    for c in colors.keys():
        data[c] /= norm

    for label, color in colors.items():
        plt.plot(data.date, data[label], color=color, label=label)        

    plt.xticks(rotation=70)
    plt.legend(loc='best')
    plt.xlabel("Date")
    plt.ylabel("Normalized Poll Percentage")

poll_plot(1044)
plt.title("Obama Job Approval")

在上面提到的代码中,我无法理解以下部分,有人可以解释一下。我完全迷失了。

data = data.rename(columns = {c: _strip(c) for c in data.columns})

#normalize poll numbers so they add to 100%    
norm = data[colors.keys()].sum(axis=1) / 100    
for c in colors.keys():
    data[c] /= norm

for label, color in colors.items():
    plt.plot(data.date, data[label], color=color, label=label)  

2 个答案:

答案 0 :(得分:1)

你在评论中说你想知道/=的含义。它被称为增强的Assignement ,在PEP 203中定义。

你有一个 int var,想要为它加一个值

n = 1
n = n + 1
print n
2

这是一种优化的方法

n = 1
n += 1

在循环中使用非常有用

n = 1
while n < 10:
    n += 1

print n
10

因此,/=使用 div 运算符代替添加

n = 4
n /= 2
print n
2

n = 10
while n > 2:
    n /= 2

print n
2

有关Augmented Assignement的更多信息,请查看Wikepedia条目。

答案 1 :(得分:0)

如果您想知道data[c] /= norm语法的含义,它类似于更常见的+=运算符。它采用赋值左侧的左侧,并指定左侧的值除以右侧值。它相当于data[c] = data[c]/norm。例如

x = 6.0
x /= 2.0

现在x的值为3.0

请尝试更清楚地了解您在问题中的具体要求,并提出您不理解的代码的特定部分。

相关问题