Python / Pandas Dataframe:自动填充缺失的行

时间:2016-03-29 18:06:21

标签: python pandas dataframe

我的目标是最终创建一个在x轴上带有日期的散点图,并在y轴上赢得(每个候选者)的代表。我不确定如何填补空白"当涉及到缺少日期。我附上了我得到的桌子的照片。

例如,我试图将3月1日作为阿拉斯加州,阿肯色州等的日期,以便可以绘制数据。

# CREATE DATAFRAME WITH DELEGATE WON/TARGET INFORMATION

import requests 
from lxml import html 
import pandas 

url = "http://projects.fivethirtyeight.com/election-2016/delegate-targets/"
response = requests.get(url)
doc = html.fromstring(response.text)

tables = doc.findall('.//table[@class="delegates desktop"]')
election = tables[0] 
election_rows = election.findall('.//tr')
def extractCells(row, isHeader=False):
    if isHeader:
        cells = row.findall('.//th')
    else:
        cells = row.findall('.//td')
    return [val.text_content() for val in cells]


def parse_options_data(table):

    rows = table.findall(".//tr")
    header = extractCells(rows[1], isHeader=True)
    data = [extractCells(row, isHeader=False) for row in rows[2:]]

    trumpdata = "Trump Won Delegates"
    cruzdata = "Cruz Won Delegates"
    kasichdata = "Kasich Won Delegates"

    data = pandas.DataFrame(data, columns=["Date", "State or Territory", "Total Delegates", trumpdata, cruzdata, kasichdata, "Rubio"])

    data.insert(4, "Trump Target Delegates", data[trumpdata].str.extract(r'(\d{0,3}$)'))
    data.insert(6, "Cruz Target Delegates", data[cruzdata].str.extract(r'(\d{0,3}$)'))
    data.insert(8, "Kasich Target Delegates", data[kasichdata].str.extract(r'(\d{0,3}$)'))

    data = data.drop('Rubio', 1)
    data[trumpdata] = data[trumpdata].str.extract(r'(^\d{0,3})')
    data[cruzdata] = data[cruzdata].str.extract(r'(^\d{0,3})')
    data[kasichdata] = data[kasichdata].str.extract(r'(^\d{0,3})')

    return df

election_data = parse_options_data(election)
df = pandas.DataFrame(election_data)
df

Picture of my table

1 个答案:

答案 0 :(得分:1)

你可以,

 data.fillna('March 1')

我建议你仔细阅读文档

http://pandas.pydata.org/pandas-docs/stable/10min.html