【问题标题】:How to create a for loop to randomly select columns from the data frame如何创建一个for循环以从数据框中随机选择列
【发布时间】:2020-08-03 17:20:54
【问题描述】:

如何创建一个 for 循环以从数据框中随机选择列,并在下一次迭代中选择 python 中的其他列。

【问题讨论】:

    标签: python pandas numpy


    【解决方案1】:

    首先从数据框中提取列列表:

    cols = df.columns
    from random import randint
    index1 = randint(0,len(cols)-1)
    index2 = randint(index1,len(cols)-1)
    sublist1 = cols[index1:index2]
    
    import numpy as np
    sublist2 = np.setdiff1d(cols,sublist1)
    

    另一种方法是使用random.sample() 并提供子列表的长度。 例如:

    col = ['a','b','c','d','e','f','g']
    sub_col = random.sample(col,4)
    ['g', 'f', 'a', 'c']
    sub_col2 =list(np.setdiff1d(col,sub_col))
    ['b', 'd', 'e']
    

    现在您可以遍历两个不同的列列表,它们没有任何共同的元素。

    【讨论】:

    • 第一组总是连续的,所以解决方案只给出一个特定类型的子集
    猜你喜欢
    • 2021-07-01
    • 2015-10-27
    • 1970-01-01
    • 2020-04-03
    • 2020-05-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多