Python/Pandas:获取列中项目的索引

我有一个包含以下列的 Pandas dataframe(df):


df["ids"]


0         18281483,1658391547

1           1268212,128064430

2                  1346542425

3  13591493,13123669,35938208

df[“编号”]


0      18281483

1       1268212

2    1346542425

3      13123669

我想找出“ids”的哪个顺序可以找到相应的“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


慕田峪9158850
浏览 254回答 3
3回答

小怪兽爱吃肉

尝试:df['output'] = df.astype(str).apply(lambda x: x['ids'].split(',').index(x['id']), axis=1)输出:                          ids          id  output0         18281483,1658391547    18281483       01           1268212,128064430     1268212       02                  1346542425  1346542425       03  13591493,13123669,35938208    13123669       1

aluckdog

这是一种方法,def index_(ids, id):    split_ = ids.split(",")    if id in split_:        return split_.index(id)    else:        return -1print(    df.assign(id = df1.id.astype(str))        .apply(lambda x: index_(x.ids, x.id), axis=1))0    01    02    03    1dtype: int64

慕丝7291255

真的不应该apply在这里使用。在更大的 Dataframes 上,它会非常慢。广播比较会工作得很好。(df["ids"].str.split(",", expand=True) == df["id"][:, None]).idxmax(1)0    01    02    03    1dtype: int64表现d = {'ids': {0: '18281483,1658391547',             1: '1268212,128064430',             2: '1346542425',             3: '13591493,13123669,35938208'},      'id': {0: '18281483',              1: '1268212',              2: '1346542425',             3: '13123669'}}df = pd.DataFrame(d)df = pd.concat([df] * 1000)%timeit (df["ids"].str.split(",", expand=True) == df["id"][:, None]).idxmax(1)                 7.51 ms ± 61.4 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)%timeit df.apply(lambda x: x['ids'].split(',').index(x['id']), axis=1)                         54.1 ms ± 249 µs per loop (mean ± std. dev. of 7 runs, 10 loops each)
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python