首页 > 解决方案 > Python / Pandas:获取列中项目的索引

问题描述

我有一个带有以下列的 Pandas 数据框(df):

df["ids"]

0         18281483,1658391547
1           1268212,128064430
2                  1346542425
3  13591493,13123669,35938208

df["id"]

0      18281483
1       1268212
2    1346542425
3      13123669

我想知道,可以找到相应“id”的“id”顺序,并在新列“order”中输出相应的值。尝试了以下代码但没有成功:

df["order"] = df["ids"].str.split(",").index(df["id"])

----------------------------------------------------------------------
TypeError: 'Int64Index' object is not callable

有语法错误吗?我手动尝试了每一行的拆分和索引功能(通过插入列表和字符串),它起作用了。

期望的输出:

df[“订单”]

0 0
1 0
2 0 
3 1

标签: pythonpandasindexing

解决方案


这是一种方法,

def index_(ids, id):
    split_ = ids.split(",")
    if id in split_:
        return split_.index(id)
    else:
        return -1


print(
    df.assign(id = df1.id.astype(str))
        .apply(lambda x: index_(x.ids, x.id), axis=1)
)

0    0
1    0
2    0
3    1
dtype: int64

推荐阅读