import numpy as np import pandas as pd from pandas import Series,DataFrame
months = {'JAN' : 1, 'FEB' : 2, 'MAR' : 3, 'APR' : 4, 'MAY' : 5, 'JUN' : 6, 'JUL' : 7, 'AUG' : 8, 'SEP' : 9, 'OCT': 10, 'NOV': 11, 'DEC' : 12} of_interest = ['Obama, Barack', 'Romney, Mitt', 'Santorum, Rick', 'Paul, Ron', 'Gingrich, Newt'] parties = { 'Bachmann, Michelle': 'Republican', 'Romney, Mitt': 'Republican', 'Obama, Barack': 'Democrat', "Roemer, Charles E. 'Buddy' III": 'Reform', 'Pawlenty, Timothy': 'Republican', 'Johnson, Gary Earl': 'Libertarian', 'Paul, Ron': 'Republican', 'Santorum, Rick': 'Republican', 'Cain, Herman': 'Republican', 'Gingrich, Newt': 'Republican', 'McCotter, Thaddeus G': 'Republican', 'Huntsman, Jon': 'Republican', 'Perry, Rick': 'Republican' }
讀取文件usa_election.txt
python
df = pd.read_csv('data/usa_election.txt') df.head()
查看文件樣式及基本信息app
【知識點】使用map函數+字典,新建一列各個候選人所在黨派party函數
df['parties'] = df['cand_nm'].map(parties) # 查看單獨一行,是否加上了'party'一列
使用np.unique()
函數查看colums:party
這一列中有哪些元素rest
df['parties'].unique()
使用value_counts()函數,統計party列中各個元素出現次數,value_counts()是Series中的,無參,返回一個帶有每一個元素出現次數的Seriescode
df['parties'].value_counts()
【知識點】使用groupby()
函數,查看各個黨派收到的政治獻金總數contb_receipt_amt
orm
df.groupby(by='parties')['contb_receipt_amt'].sum()
查看具體天天各個黨派收到的政治獻金總數contb_receipt_amt 。使用groupby([多個分組參數])索引
df.groupby(by=['contb_receipt_dt','parties'])['contb_receipt_amt'].sum()
將表中日期格式轉換爲'yyyy-mm-dd'
。日期格式,經過函數加map方式進行轉換ip
def func(s): # 20-JUN-11 day,month,year = s.split('-') month = months[month] return f'20{year}-{month}-{day}' df['contb_receipt_dt'] = df['contb_receipt_dt'].apply(func)
獲得天天各政黨所收政治獻金數目。 考察知識點:groupby(多個字段)
數據分析
cand_nm_df = df.groupby(by=['cand_nm','contb_receipt_amt'])['contb_receipt_dt'].sum() cand_nm_df
【知識點】使用 unstack() 將上面所得數據中的party行索引變成列索引pandas
查看老兵(捐獻者職業)DISABLED VETERAN主要支持誰 :查看老兵們捐贈給誰的錢最多
#獲取老兵對應的行數據 df['contbr_occupation'] == 'DISABLED VETERAN' old_bing_df = df.loc[df['contbr_occupation'] == 'DISABLED VETERAN'] old_bing_df.groupby(by='cand_nm')['contb_receipt_amt'].sum()
把索引變成列,Series變量.reset_index()
找出各個候選人的捐贈者中,捐贈金額最大的人的職業以及捐獻額 .經過query("查詢條件來查找捐獻人職業")
df['contb_receipt_amt'].max() df.query('contb_receipt_amt == 1944042.43')