【问题标题】:Python: Return column index given a condition is metPython:在满足条件的情况下返回列索引
【发布时间】:2021-09-01 02:18:09
【问题描述】:

如果满足特定条件,我想获取列索引。

例如,我想获取所有包含 0 的列的索引。在这种情况下,它将是 [0,1] -->(A 列和 B 列)。

df = {'A': [0,1,2,3,4,5], 
      'B': [3,4,0,5,6,5], 
      'C': [1,2,3,4,5,6],
      'D': [7,8,9,8,7,6]} 

df = pd.DataFrame(df)

谢谢!

【问题讨论】:

    标签: python arrays pandas list numpy


    【解决方案1】:

    使用np.where:

    index_array = np.where(df.eq(0).any())[0] # prints array([0, 1])
    index_array = np.where(~df.eq(0).any())[0]  # prints array([2, 3])
    

    如果您需要列名:

    col_list = df.columns[df.eq(0).any()] # prints Index(['A', 'B'], dtype='object')
    

    【讨论】:

    • 非常感谢!我现在尝试使用以下内容返回所有不包含“0”的列:index_array = set(np.where(df1 != 0)[1]) 但它返回 {0, 1, 2, 3, 4}。你能纠正我吗?
    • @student214 使用:np.where(~df.eq(0).any())
    【解决方案2】:

    这应该可以帮助你。

    (df == 0).any(axis=1)
    op:
    0     True
    1    False
    2     True
    3    False
    4    False
    5    False
    dtype: bool
    

    【讨论】:

      猜你喜欢
      • 2020-02-09
      • 2019-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-22
      相关资源
      最近更新 更多