首页 > 解决方案 > 无法根据条件获取索引

问题描述

我试图获取具有特定值的 node_id 列的索引,但我的代码不返回任何内容,而是返回选项列的索引。我无法说出两列之间存在差异的原因。任何人都可以给我提示吗?太感谢了。

client_data = """node_id,option,before_id
    1,A,
    5,A,4
    3,B,2
    4,C,1
    8,C,2
    6,A,
    2,A,1
    7,C,6
    """

    df = pd.read_csv(io.StringIO(client_data), dtype='string', error_bad_lines=False)
    before_ind = df.loc[df['node_id'] == 1].index
    print(before_ind)
output of before_ind = df.loc[df['node_id'] == 1].index

Int64Index([], dtype='int64')
If I do before_ind = df.loc[df['option'] == 'C'].index

  node_id option before_id
3       4      C         1
4       8      C         2
7       7      C         6

标签: python-3.xpandas

解决方案


'node id' 的值是字符串,所以使用:

before_ind = df.loc[df['node_id'] == '1'].index

您可以通过使用.dtypes属性进行交叉验证:

print(df.dtypes)

#output:
node_id      string
option       string
before_id    string
dtype: object

或者

使用以下方法将“node_id”类型化为 int astype()

df['nodr id']=df['node id'].astype(int) 
#then use:
before_ind = df.loc[df['node_id'] == 1].index

或者

不要在read_csv()方法中使用 dtype 参数,让 pandas 操纵 dtypes:

df = pd.read_csv(io.StringIO(client_data), error_bad_lines=False)

推荐阅读