3 回答

TA贡献1852条经验 获得超1个赞
尝试:
df['output'] = df.astype(str).apply(lambda x: x['ids'].split(',').index(x['id']), axis=1)
输出:
ids id output
0 18281483,1658391547 18281483 0
1 1268212,128064430 1268212 0
2 1346542425 1346542425 0
3 13591493,13123669,35938208 13123669 1

TA贡献1847条经验 获得超7个赞
这是一种方法,
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

TA贡献1859条经验 获得超6个赞
真的不应该apply在这里使用。在更大的 Dataframes 上,它会非常慢。广播比较会工作得很好。
(df["ids"].str.split(",", expand=True) == df["id"][:, None]).idxmax(1)
0 0
1 0
2 0
3 1
dtype: 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)
添加回答
举报