![](/img/trans.png)
[英]Is there a way to get datetime ranges based on the value of another column in a pandas dataframe?
[英]get column value based on another column with list of strings in pandas dataframe
我试过这个链接 。 但它对我下面给出的例子不起作用。 我尝试了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
来删除first和last []
或者使用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
你也可以使用:
df.loc[df['Item'].str.contains('Phone'), ['RelatedItem', 'CountinInventory']]
错误too many indexers
是因为df.loc []需要带有标签的标签,列表或切片对象的数组。 但是你给了一系列'标签'。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.