【问题标题】:CSV File to Array without the last value没有最后一个值的 CSV 文件到数组
【发布时间】:2020-12-22 03:52:08
【问题描述】:

所以我对 Python 和神经网络场景还是很陌生。我编写了一些神经网络(主要是 CNN),但这些只是一些测试项目。我在教程等的大量帮助下完成了它们。现在我正在尝试编写一个简单的神经网络,通过一些“指标”来预测学生的成绩。问题是“变量”没有按列分隔。我需要将指标分成一个没有最后一个的所有指标的列表和一个有最后一个但没有其他东西的列表。我也很确定我需要将“是”和“否”转换为 1 和 0。

数据集:https://archive.ics.uci.edu/ml/datasets/student+performance

【问题讨论】:

    标签: python neural-network dataset


    【解决方案1】:

    读取 csv 数据:

    • 使用 read_csv 将数据加载到数据框中。指定分号作为分隔符。
    • 使用 columns 集合调整要从主数据框中提取的列
    • 使用 apply 将列从 yes\no 转换为 1\0

    这里是 csv 文件的前 5 行供参考:

    school;sex;age;address;famsize;Pstatus;Medu;Fedu;Mjob;Fjob;reason;guardian;traveltime;studytime;failures;schoolsup;famsup;paid;activities;nursery;higher;internet;romantic;famrel;freetime;goout;Dalc;Walc;health;absences;G1;G2;G3
    "GP";"F";18;"U";"GT3";"A";4;4;"at_home";"teacher";"course";"mother";2;2;0;"yes";"no";"no";"no";"yes";"yes";"no";"no";4;3;4;1;1;3;6;"5";"6";6
    "GP";"F";17;"U";"GT3";"T";1;1;"at_home";"other";"course";"father";1;2;0;"no";"yes";"no";"no";"no";"yes";"yes";"no";5;3;3;1;1;3;4;"5";"5";6
    "GP";"F";15;"U";"LE3";"T";1;1;"at_home";"other";"other";"mother";1;2;3;"yes";"no";"yes";"no";"yes";"yes";"yes";"no";4;3;2;2;3;3;10;"7";"8";10
    "GP";"F";15;"U";"GT3";"T";4;2;"health";"services";"home";"mother";1;3;0;"no";"yes";"yes";"yes";"yes";"yes";"yes";"yes";3;2;2;1;1;5;2;"15";"14";15
    

    下面是解析csv数据的代码:

    import pandas as pd
    
    df = pd.read_csv("student/student-mat.csv", sep=';')  # read csv
    dfmain  = df[df.columns[:-3]]  # no grade columns
    dfgrade = df[df.columns[-3:]]  # grade columns
    
    for c in df.columns[16:24]:  # yes\no columns
       dfmain[c] = dfmain[c].apply(lambda x: 0 if str(x)=='no' else 1).astype(int) # no=0, yes=1
    
    print(dfmain[df.columns[16:24]])  # yes\no columns
    

    输出(是\否列)

         famsup  paid  activities  nursery  higher  internet  romantic  famrel
    0         0     0           0        1       1         0         0       1
    1         1     0           0        0       1         1         0       1
    2         0     1           0        1       1         1         0       1
    3         1     1           1        1       1         1         1       1
    4         1     1           0        1       1         0         0       1
    ..      ...   ...         ...      ...     ...       ...       ...     ...
    

    【讨论】:

    • 感谢您的帮助。在很多方面帮助了我
    • 很高兴听到。请将答案标记为已接受,以从“无答案”列表中删除该帖子。谢谢,
    猜你喜欢
    • 1970-01-01
    • 2015-02-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多