2016年美国大选民意调查数据统计:

  • 项目地址:https://www.kaggle.com/fivethirtyeight/2016-election-polls
  • 该数据集包含了2015年11月至2016年11月期间对于2016美国大选的选票数据,共27列数据

示例代码1 :

# loadtxt
import numpy as np

# csv 名逗号分隔值文件
filename = './presidential_polls.csv'

# 通过loadtxt()读取本地csv文件 
data_array = np.loadtxt(filename,      # 文件名
                        delimiter=',', # 分隔符
                        dtype=str,     # 数据类型,数据是Unicode字符串
                        usecols=(0,2,3)) # 指定读取的列号

# 打印ndarray数据,保留第一行
print(data_array, data_array.shape)

运行结果:

[["b'cycle'" "b'type'" "b'matchup'"]
 ["b'2016'" 'b\'"polls-plus"\'' 'b\'"Clinton vs. Trump vs. Johnson"\'']
 ["b'2016'" 'b\'"polls-plus"\'' 'b\'"Clinton vs. Trump vs. Johnson"\'']
 ..., 
 ["b'2016'" 'b\'"polls-only"\'' 'b\'"Clinton vs. Trump vs. Johnson"\'']
 ["b'2016'" 'b\'"polls-only"\'' 'b\'"Clinton vs. Trump vs. Johnson"\'']
 ["b'2016'" 'b\'"polls-only"\'' 'b\'"Clinton vs. Trump vs. Johnson"\'']] (10237, 3)

示例代码2:

import numpy as np
# 读取列名,即第一行数据
with open(filename, 'r') as f:
    col_names_str = f.readline()[:-1] # [:-1]表示不读取末尾的换行符'\n'

# 将字符串拆分,并组成列表
col_name_lst = col_names_str.split(',')

# 使用的列名:结束时间,克林顿原始票数,川普原始票数,克林顿调整后票数,川普调整后票数
use_col_name_lst = ['enddate', 'rawpoll_clinton', 'rawpoll_trump','adjpoll_clinton', 'adjpoll_trump']

# 获取相应列名的索引号
use_col_index_lst = [col_name_lst.index(use_col_name) for use_col_name in use_col_name_lst]

# 通过genfromtxt()读取本地csv文件,
data_array = np.genfromtxt(filename,      # 文件名
                        delimiter=',', # 分隔符
                        #skiprows=1, # 跳过第一行,即跳过列名
                        dtype=str,     # 数据类型,数据不再是Unicode字符串
                        usecols=use_col_index_lst)# 指定读取的列索引号


# genfromtxt() 不能通过 skiprows 跳过第一行的
# ['enddate' 'rawpoll_clinton' 'rawpoll_trump' 'adjpoll_clinton' 'adjpoll_trump']

# 去掉第一行
data_array = data_array[1:]

# 打印ndarray数据
print(data_array[1:], data_array.shape)

运行结果:

[['10/30/2016' '45' '46' '43.29659' '44.72984']
 ['10/30/2016' '48' '42' '46.29779' '40.72604']
 ['10/24/2016' '48' '45' '46.35931' '45.30585']
 ..., 
 ['9/22/2016' '46.54' '40.04' '45.9713' '39.97518']
 ['6/21/2016' '43' '43' '45.2939' '46.66175']
 ['8/18/2016' '32.54' '43.61' '31.62721' '44.65947']] (10236, 5)

Copyright © BigCat all right reserved,powered by Gitbook「Revision Time: 2017-04-24 22:50:07」