zoukankan      html  css  js  c++  java
  • pandas清洗数据实用代码

    github博客传送门
    csdn博客传送门

    先创建一个可操作的DataFrame -> pandas的一种数据结构

    dic = {'name': {'a': "abc", 'b': "boc", 'c': "ccb", 'd': "icbc", 'e': "boc"},
            'data': {'a': "农业银行", 'b': "中国银行", 'c': "建设银行", 'd': "工商银行", 'e': "中国银行"},
            'one': {'a': 1, 'b': 0, 'c': 0, 'd': 0, 'e': 0},
            'two': {'a': 0, 'b': 1, 'c': 0, 'd': 0, 'e': 1},
            'three': {'a': 0, 'b': 0, 'c': 1, 'd': 0, 'e': 0},
            'four': {'a': 0, 'b': 0, 'c': 0, 'd': 1, 'e': 0}}  # 创建了一个嵌套的字典
    
    df = pd.DataFrame(dic)  # 将这个嵌套字典转换为DataFrame
    print(df)                # 打印出转换后的DataFrame
    

    输出是这样的:

    name data one two three four
    a abc 农业银行 1 0 0 0
    b boc 中国银行 0 1 0 0
    c ccb 建设银行 0 0 1 0
    d icbc 工商银行 0 0 0 1
    e boc 中国银行 0 1 0 0

    一. 删除指定列

    def drop_multiple_col(col_names_list, df):
        df.drop(col_names_list, axis=1, inplace=True)
        return df
    
    print(drop_multiple_col('one', df))
    

    删除指定列 'one'后输出:

    name data two three four
    a abc 农业银行 0 0 0
    b boc 中国银行 1 0 0
    c ccb 建设银行 0 1 0
    d icbc 工商银行 0 0 1
    e boc 中国银行 1 0 0

    二. 检查每列缺失数据的数量

    def check_missing_data(df):
        return df.isnull().sum().sort_values(ascending=False)
    print(check_missing_data(df))
    

    检查结果如下

    name 0
    data 0
    one 0
    two 0
    three 0
    four 0

    三. 增加一列label

    def create_label(class_dict, df):
        df['label'] = temp['name'].apply(lambda x: class_dict[x])  # 增加一列label并填加值为 字典对应的值
        return df
    class_dict = {'abc': 0, 'boc': 1, 'ccb': 2, 'icbc': 3}  # 转label字典
    print(create_label(class_dict, df))
    

    增加label后的输出:

    然后再删除不需要的列,就只剩下数据和标签了

    name data one two three four label
    a abc 农业银行 1 0 0 0 0
    b boc 中国银行 0 1 0 0 1
    c ccb 建设银行 0 0 1 0 2
    d icbc 工商银行 0 0 0 1 3
    e boc 中国银行 0 1 0 0 1

    四. 替换或删除列中字符串

    替换 data 列中的 '银行' 字符串为 空

    def remove_col_str(df):
        df['data'].replace('银行', '', regex=True, inplace=True)
    remove_col_str(df)
    print(df)
    

    替换后的输出为:

    name data one two three four
    a abc 农业 1 0 0 0
    b boc 中国 0 1 0 0
    c ccb 建设 0 0 1 0
    d icbc 工商 0 0 0 1
    e boc 中国 0 1 0 0
    print_r('点个赞吧');
    var_dump('点个赞吧');
    NSLog(@"点个赞吧!")
    System.out.println("点个赞吧!");
    console.log("点个赞吧!");
    print("点个赞吧!");
    printf("点个赞吧!
    ");
    cout << "点个赞吧!" << endl;
    Console.WriteLine("点个赞吧!");
    fmt.Println("点个赞吧!")
    Response.Write("点个赞吧");
    alert(’点个赞吧’)
    
  • 相关阅读:
    Web性能压力测试工具之ApacheBench(ab)详解
    微服务监控之三:Prometheus + Grafana Spring Boot 应用可视化监控
    Sentinel-dashboard
    Java8之默认方法和静态接口方法
    蓝绿部署、红黑部署、AB测试、灰度发布、金丝雀发布、滚动发布的概念与区别
    JAVA8 十大新特性详解
    Java链式方法 连贯接口(fluent interface)
    分布式计算概念一览
    Gradle学习
    Java堆外内存之七:JVM NativeMemoryTracking 分析堆外内存泄露
  • 原文地址:https://www.cnblogs.com/Mrzhang3389/p/11166800.html
Copyright © 2011-2022 走看看