我试图获取具有特定值的 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
最佳答案
'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
或
使用 astype()
方法将 'node_id' 类型化为 int:
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)
关于python-3.x - 无法根据条件获取索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68466196/