python-3.x - 无法根据条件获取索引

标签 python-3.x pandas

我试图获取具有特定值的 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/

相关文章:

python - 如何在python中遍历矩阵

python-3.x - 确定路径在类构造函数中是否有效

python-3.x - 如何从 Python 代码对象构造可调用对象?

python - 合并相邻的二维多边形

python - 循环 Pandas 对象列表表现出奇怪的行为

python - NumericType 错误 - 转换为 float 进行计算?

python - 使用多个 isin 子句的 Pandas 索引

python - 使用 Jupyter Notebook 查看从 Python 运行的 MATLAB 代码的输出

Python问题: reading multiple json files from a folder load only one json

pandas - Pandas 数据框python中的偏相关系数