Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/332.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/18.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python-finding从列表中提取相同的值,并计算连续值之间的差异_Python_Python 3.x_Data Science - Fatal编程技术网

Python-finding从列表中提取相同的值,并计算连续值之间的差异

Python-finding从列表中提取相同的值,并计算连续值之间的差异,python,python-3.x,data-science,Python,Python 3.x,Data Science,我正在dataquest上学习python,并试图解决这个问题 编写一个函数,提取不同年份的相同值,并计算连续值之间的差异,以显示出生数是增加还是减少。 例如,从1994年到2003年,每年星期六的出生人数是如何变化的 我正试图在Jupyter解决这个问题。我是python新手,不知道如何着手解决这个问题 此处的数据输入为CSV格式: 我也在做同一个项目。我已经分享了你需要的部分代码。我有项目的.ipynb文件。您可能还想看看我的函数结果。干杯 def read_csv(birth_data_f

我正在dataquest上学习python,并试图解决这个问题

编写一个函数,提取不同年份的相同值,并计算连续值之间的差异,以显示出生数是增加还是减少。 例如,从1994年到2003年,每年星期六的出生人数是如何变化的

我正试图在Jupyter解决这个问题。我是python新手,不知道如何着手解决这个问题

此处的数据输入为CSV格式:


我也在做同一个项目。我已经分享了你需要的部分代码。我有项目的.ipynb文件。您可能还想看看我的函数结果。干杯

def read_csv(birth_data_file):
    raw_data = open(birth_data_file, "r").read()
    raw_data = raw_data.split("\n")
    string_list = raw_data[1:]
    final_list = []
    for data in string_list:
        int_fields = []
        string_fields = data.split(",")
        for string_field in string_fields:
            field = int(string_field)
            int_fields.append(field)
        final_list.append(int_fields)
    return(final_list)


def calc_counts(data, column):
    births_counts = {}
    if not column > 0 and column <= 4:
        return("'column' must be either 1, 2, 3, or 4")
    else:
        for instance in data:
            field = instance[column-1]
            births  = instance[4]
            if field in births_counts.keys():
                births_counts[field] += births
            else:
                births_counts[field] = births
        return(births_counts)


# Write a function that extracts the same values across years and calculates the
# differences between consecutive values to show if number of
# births is increasing or decreasing.

def check_birth_growth(birth_data_file):
    cdc_list = read_csv(birth_data_file)
    cdc_year_births = calc_counts(cdc_list, 1)
    previous_year_birth = 0
    previous_birth_diff = 0
    for year, total_births in cdc_year_births.items():
        current_year_birth = int(total_births)
        if previous_year_birth == 0:
            growth_status = "Growth of births in {} not available.".format(year)
            print(growth_status)
            previous_year_birth = current_year_birth
        else:
            if current_year_birth > previous_year_birth:
                growth_status = "Births increased in {}.".format(year)
                print(growth_status)
                previous_year_birth = current_year_birth
            elif current_year_birth < previous_year_birth:
                growth_status = "Births decreased in {}.".format(year)
                print(growth_status)
                previous_year_birth = current_year_birth
            elif current_year_birth == previous_year_birth:
                growth_status = "Births in {} was same as previous year.".format(year)
                print(growth_status)
                previous_year_birth = current_year_birth
def read_csv(出生数据文件):
原始数据=打开(出生数据文件,“r”).read()
原始数据=原始数据。拆分(“\n”)
字符串列表=原始数据[1:]
最终清单=[]
对于字符串列表中的数据:
int_字段=[]
string_fields=data.split(“,”)
对于字符串字段中的字符串字段:
字段=int(字符串\字段)
int_fields.append(字段)
最终列表。追加(整数字段)
返回(最终列表)
def calc_计数(数据,列):
出生人数={}
如果不是列>0和列上一年出生:
growth_status=“出生人数以{}的形式增加。”。格式(年)
打印(增长状态)
上一年出生=当前年出生
如果当前年出生<上一年出生:
growth_status=“出生人数以{}形式减少。”。格式(年)
打印(增长状态)
上一年出生=当前年出生
elif本年出生==上一年出生:
growth_status=“在{}出生的婴儿与上一年相同。”。格式(年)
打印(增长状态)
上一年出生=当前年出生
def calc_diff(文件名、日期一、日期二、列、列值):
出生率结果=[]
以前的出生率=0
对于文件名中的行:
年份=行[0]
当前出生率=第[4]行
时间单位=行[列]
如果年份在范围内(日期1,日期2):
如果时间单位为列值:
出生率差异=(当前出生率-先前出生率)
如果出生率差异>0:
增长状况=“增加”
以前的出生率=当前的出生率
elif出生率差异<0:
增长状况=“减少”
以前的出生率=当前的出生率
elif出生率差异==0:
增长状态=“静态”
以前的出生率=当前的出生率
出生率结果。追加([出生率差异,增长率状态,第[0]行])
返回出生率结果

我刚开始学习python,你能告诉我如何运行这些代码示例(birth_difference=calc_diff(cdc_list,4,4,0,4)),没有弹出答案。我相信上面的代码只统计连续年份、周期之间的出生差异,而没有为不同的参数提供机会-例如,1月或周日历年出生差异

在以下功能中,您可以执行此操作,例如,使用输入查看星期一出生数年的差异:=3和=1

def delta_year(input_list, column, value): # Column to loop over, value to compare over years

    column_year_count = {} # Create dictionary to get attribute yearly count

    for each in input_list:
        attribute = each[column]
        year = each[0]
        births = each[4]
        if attribute == value:
            if year in column_year_count:
                column_year_count[year] += births
            else:
                column_year_count[year] = births

    column_year_count_list = [] # Create list to order years to get consecutive years

    for key, value in column_year_count.items():
        temp = [key,value]
        column_year_count_list.append(temp)

    column_year_delta = {} # Create dictionary to insert ordered years & delta values

    for i in range(0,len(column_year_count_list)): # Loop over list index
        for j in range(0,len(column_year_count_list)): # Loop over second list index
            delta_year = column_year_count_list[j][0] - column_year_count_list[i][0] # Tally delta between years
            if delta_year == 1: # Select consecutive years only
                delta_year_births = column_year_count_list[j][1] - column_year_count_list[i][1]
                column_year_delta[column_year_count_list[j][0]] = delta_year_births
    return column_year_delta

您可以从澄清需求开始。年份和出生人数的数据格式是什么(数据本身的格式以及如何与其他数据一起存储)?您的函数如何访问该数据?所需的输出格式是什么?是否有其他要求或偏好?我们无法帮助您,除非您了解并理解这些要求,然后将其包括在您的问题中。检查和。非常感谢。我在问题中加入了更多的信息。如果这还不够,请告诉我。需要更多关于输入的信息,而您对输出却只字不提。驱动器上的csv文件是否与功能模块位于同一文件夹中?该文件是否保证有该名称,从1994-01-01到2003-12-31,每天只有一行,行按时间顺序排列,没有重复或缺失的日期,标题行和数据行完整且格式正确,等等。?关于周六出生的问题是唯一需要的产出吗?等等您是否意识到您的代码实际上并没有访问数据?是的,请回答您的问题。我正在使用Jupyter项目进行学习。嘿@iprateekk!很荣幸!:)非常感谢。你真的帮了大忙。你应该对你的代码添加解释,说明为什么你的解决方案更好,否则你可能得不到选票。它还将帮助新的程序员了解您所做的工作。
def calc_diff(filename, date_one, date_two, column, column_value):
birth_rate_result = []
previous_birth_rate = 0

for row in filename:
    year = row[0]
    current_birth_rate = row[4]
    time_unit = row[column]
    if year in range(date_one,date_two):
        if time_unit is column_value:
            birth_rate_diff = (current_birth_rate - previous_birth_rate)
            if birth_rate_diff > 0:
                growth_status = "increased"
                previous_birth_rate = current_birth_rate
            elif birth_rate_diff < 0:
                growth_status = "decreased"
                previous_birth_rate = current_birth_rate
            elif birth_rate_diff == 0:
                growth_status = "static"
                previous_birth_rate = current_birth_rate

            birth_rate_result.append([birth_rate_diff, growth_status,row[0]])

return birth_rate_result 
def delta_year(input_list, column, value): # Column to loop over, value to compare over years

    column_year_count = {} # Create dictionary to get attribute yearly count

    for each in input_list:
        attribute = each[column]
        year = each[0]
        births = each[4]
        if attribute == value:
            if year in column_year_count:
                column_year_count[year] += births
            else:
                column_year_count[year] = births

    column_year_count_list = [] # Create list to order years to get consecutive years

    for key, value in column_year_count.items():
        temp = [key,value]
        column_year_count_list.append(temp)

    column_year_delta = {} # Create dictionary to insert ordered years & delta values

    for i in range(0,len(column_year_count_list)): # Loop over list index
        for j in range(0,len(column_year_count_list)): # Loop over second list index
            delta_year = column_year_count_list[j][0] - column_year_count_list[i][0] # Tally delta between years
            if delta_year == 1: # Select consecutive years only
                delta_year_births = column_year_count_list[j][1] - column_year_count_list[i][1]
                column_year_delta[column_year_count_list[j][0]] = delta_year_births
    return column_year_delta