• python dataframe筛选列表的值转为list【常用】


      网上方法参差不齐,无注释解释不好秒懂,没有自己想要的,故自己试验一番~

    1. 筛选列表中,当b列中为’1’时,所有c的值,然后转为list
    2 .筛选列表中,当a列中为'one',b列为'1'时,所有c的值,然后转为list
    3 .将a列整列的值,转为list(两种)
    4. 筛选列表,当a=‘one’时,取整行所有值,然后转为list

    具体看下面代码:

    import pandas as pd
    from pandas import DataFrame
    
    
    df = DataFrame([['one', '1', ''],
                    ['one', '1', ''],
                    ['two', '2', ''],
                    ['three', '3', ''],
                    ['four', '1', ''],
                    ['five', '5', '']],
            columns=['a', 'b', 'c'])
    
    print(df)
    """
    out:
           a  b  c
    0    one  1  一
    1    one  1  一
    2    two  2  二
    3  three  3  三
    4   four  1  四
    5   five  5  五
    """
    
    # 筛选列表中,当b列中为’1’时,所有c的值,然后转为list
    b_c = df.c[df['b'] == '1'].tolist()
    print(b_c)
    
    # out:  ['一', '一', '四']
    
    # 筛选列表中,当a列中为'one',b列为'1'时,所有c的值,然后转为list
    a_b_c = df.c[(df['a'] == 'one') & (df['b'] == '1')].tolist()
    print(a_b_c)
    
    # out:  ['一', '一']
    
    # 将a列整列的值,转为list(两种)
    a_list_1 = df.a.tolist()
    a_list_2 = df['a'].tolist()
    print(a_list_1, "
    ", a_list_2)
    
    """
    out:
    ['one', 'one', 'two', 'three', 'four', 'five'] 
     ['one', 'one', 'two', 'three', 'four', 'five']
    """
    
    # 筛选列表,当a=‘one’时,取整行所有值,然后转为list
    a_line = df[df['a'] == 'two'].values.tolist()
    print(a_line)
    
    # out:  [['two', '2', '二']]

     如有错误,请及时指正,谢谢!

  • 相关阅读:
    关于面试的有意义问题
    Web测试方法总结
    alwayson05-安装sql server
    alwayson03-安装故障转移
    always on
    alwayson02-各个节点加入域
    alwayson01-搭建域环境
    undo log和redo log
    mysql事务隔离级别
    Ajax
  • 原文地址:https://www.cnblogs.com/4wheel/p/11258107.html
Copyright © 2020-2023  润新知