python - 根据熊猫数据框中字符串列表的另一列获取列值
问题描述
我试过链接。但它不适用于我下面给出的示例。我尝试了 loc[0] 的输出。我试过.item()。但这些都没有帮助我。
>>> df2 = pd.DataFrame({ 'Item':['[Phone]', '[Watch]', '[Pen]', '[Pencil]', '[Knife]'], 'RelatedItem': ['[Phone cover]', '[Watch strap]', '[Pen cap]', '[Pencil lead]', '[fork]'], 'CountinInventory':['20','50','40','80','90']})
>>> df2
Item RelatedItem CountinInventory
0 [Phone] [Phone cover] 20
1 [Watch] [Watch strap] 50
2 [Pen] [Pen cap] 40
3 [Pencil] [Pencil lead] 80
4 [Knife] [fork] 90
>>> df2.loc[df2['Item'] == 'Phone', 'RelatedItem']
Series([], Name: RelatedItem, dtype: object)
>>> df2.loc[df2['Item'] == 'Phone', 'RelatedItem', 'CountinInventory']
pandas.core.indexing.IndexingError: Too many indexers
我有这些数据,当我喂食时Phone
,我需要以Phone cover
价值CountinInventory
作为我的答案。请告知我在这里犯了什么错误。
解决方案
我相信你需要str
删除第一个和最后一个[]
或使用str.strip
:
mask = df2['Item'].str[1:-1] == 'Phone'
#alternative solution
#mask = df2['Item'].str.strip('[]') == 'Phone'
print (mask)
0 True
1 False
2 False
3 False
4 False
Name: Item, dtype: bool
如果没有缺失值是可能的使用list comprehension
,如果大数据更快:
mask = [x[1:-1] == 'Phone'for x in df2['Item']]
mask = [x.strip('[]') == 'Phone'for x in df2['Item']]
print (mask)
[True, False, False, False, False]
最后选择多列使用list
:
df3 = df2.loc[mask, ['RelatedItem', 'CountinInventory']]
print (df3)
RelatedItem CountinInventory
0 [Phone cover] 20
推荐阅读
- c# - Autofac:即时为每个实例创建嵌套范围
- vba - Excel 宏 - 禁用“文件现在可用于编辑”消息
- java - 无法将类添加到 Eclipse 氧气项目
- javascript - 用户与 javascript 的交互?
- openmdao - BsplinesComp 上的约束
- typescript - 打字稿 tsc --declaration
- ios - 在 PDFView 表单域中配置键盘设置
- fiware - 无法使用 MySQL 代理运行 Cygnus
- python-3.x - 查询多个 SQLalchemy ORM
- kubernetes - 如何在主节点上运行 kube-proxy?