【问题标题】:How can I get the index of the row where a value has a certain value?如何获取值具有特定值的行的索引?
【发布时间】:2020-08-07 16:31:32
【问题描述】:

早上好,

我有一个只有 True 和 False 值的数据框,并且想要获取 True 值退出的行索引。 我试过这个:

[i for i in df_str[df_str.columns.values] if i== True]

但这会返回一个空数组。 我该怎么做?

【问题讨论】:

  • 您是在单个列中还是在数据框中的任何列中寻找“真”?
  • @Roy2012 是的,我正在搜索 True 值,我想要索引
  • 再次 - 在数据框中的特定列中,还是在许多列之一中?输入的结构是什么?
  • @Roy2012 在我要搜索的所有列中
  • 请提供具有预期输出的示例数据

标签: python pandas dataframe


【解决方案1】:

这是一种方法。为了演示,我使用合成数据。

df = pd.DataFrame({"a": np.random.choice([True, False], 10), 
              "b": np.random.choice([True, False], 10)}) 

print(df)
#        a      b
# 0  False   True
# 1   True  False
# 2  False   True
# 3   True   True
# 4  False  False
# 5   True  False
# 6  False   True
# 7   True  False
# 8   True  False
# 9   True   True

# 'a' and 'b' are the columns you'd like to search
df[df[["a", "b"]].sum(axis=1) > 0].index.to_list()
# ==> [0, 1, 2, 3, 5, 6, 7, 8, 9]

【讨论】:

    【解决方案2】:

    解决办法

    # for single column
    df.index[df['col_name'] == True].tolist()
    
    #for multiple columns
    df[df[["a", "b"]].sum(axis=1) > 0].index.to_list()
    

    【讨论】:

    • 我要搜索所有列,而不是特定列
    【解决方案3】:

    获取存在True 的索引(对于提供的示例)的最佳方法是使用any。以下代码将为您提供特定行中任何值为True 的所有索引。

    df=pd.DataFrame({"A":[True, False, False, True],"B":[True, True, False, False]})
    indices=df[df.any(axis=1)].index
    

    预期输出

    Int64Index([0, 1, 3], dtype='int64')
    

    【讨论】:

      猜你喜欢
      • 2018-05-31
      • 2021-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-16
      • 2021-03-06
      • 1970-01-01
      相关资源
      最近更新 更多