python-3.x - 无法根据条件获取索引
问题描述
我试图获取具有特定值的 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
或者
使用以下方法将“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)
推荐阅读
- sql - 如何在sql b2b中为每个ID分组找到最大值
- python - 无法安装张量流压缩
- python - 24小时内的各种时间,但当它跳到第二天时它们变成负时间
- pine-script - pine 脚本中指示器功能的指示器
- c# - 我可以在构建 .net-core 应用程序后添加本地化资源 (*.resx) 吗?
- angular - Karma ng 测试未在控制台中显示构建错误
- r - 在 R 中运行 LightGBM 时出错“不支持从 'data.frame' 构建”
- vbscript - How to Run a file with a variable name in vbscript
- node.js - 如何在使用 nodejs 链码从超级账本结构 v 1.4 中的链码中获取记录时设置偏移量和限制?
- elasticsearch - 如何在 Kibana 中写入给定的索引模式?