python - 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
解决方案
这是一种方法,
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
推荐阅读
- excel - 如何将excel的列数据转换为行数据
- php - 实现具有无限可能的 MYSQLI Bind Param
- json - 将获取的数据分配给 React 状态后得到“未定义”
- wordpress - Youtube 嵌入在 WP 编辑器中看起来不错,但在预览页面中过大
- reactjs - Web 套接字在反应应用程序中不断断开连接。后端是 Nestjs
- python - 点安装 opencv-contrib-python
- python - 使用提取的咬痕重新创建图像并保存在 txt 文件中
- python-3.x - 在 Firefox 而不是 Chrome (Selenium Python) 中寻找此代码
- angular - 如何从 Material Icon Buttons 中删除边框和背景
- java - 在 Mongo 中存储具有实例化和空集合的嵌入式文档